GuzzleHttp Запрос не работает - PullRequest
0 голосов
/ 30 апреля 2020

Я пытаюсь сделать HTTP-запрос от моего бэкэнда с пакетом guzzlehttp / guzzle в symfony 3.4 на мой NodeJS тестовый сервер. Я попытался проверить мой nodeJS сервер с почтальоном и cURL, и он работает, но не с моим бэкэндом.

это мой код:

  • в PartnerController. php:
    /**
     * @POST("/partner/searchNurseToUser")
     */
    public function searchNurseAction(Request $request)
    {

        $client = new Client(['base_uri' => 'http://172.18.0.5:9000']);  

        $nurseFirstname = htmlspecialchars($request->request->get('nurseFirstname'));
        $nurseLastname = htmlspecialchars($request->request->get('nurseLastname'));
        $nursePhone = htmlspecialchars($request->request->get('nursePhoneNumber'));
        $nursePostalCode = htmlspecialchars($request->request->get('nursePostalCode'));
        $nurseCity = htmlspecialchars($request->request->get('nurseCity'));


        try {
            $response = $client->request('POST', 'partner/pros/', [
                'json' => [
                    'name' => $nurseFirstname . ' ' . $nurseLastname, 
                    'city' => $nurseCity,  
                    'phone' => $nursePhone,
                    'zipcode' => $nursePostalCode

                ]
            ]);
  • в приложении. js:
const bodyParser = require('body-parser');


const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })) 

// Define routes
app.use('/partner/', require('./routes/api/partner'));


const port = 9000;
app.listen(port, function() {
    console.log('Listening on port 9000!')
})
  • partner. js:
const router = express.Router();

router.post('/pros', async (req, res) => {
    const { name, email, phone, city, zipcode } = req.body;

    try {
        let response = {};
        if (name || email || phone || city || zipcode) {
            response = {
                "data": [
                    {
                    "civility": "F",
                    "firstname": "Adeline",
                    "lastname": "Dupont"
                    }
                ]
            }
        } else {
            response = [];
        }

        return res.json(response).status(200);
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
})

module.exports = router;

Но Почтальон возвращает это сообщение об ошибке:

Error GuzzleHttp Message Error "Resources are not supported in serialized data. Path: GuzzleHttp\\Psr7\\Stream".

Спасибо за помощь!

1 Ответ

0 голосов
/ 30 апреля 2020

Я нашел решение !!

Просто используйте JsonResponse в возвращении моей функции searchNurseAction!

   /**
     * @POST("/partner/searchNurseToUser")
     */
    public function searchNurseAction(Request $request)
    {

        $client = new Client(['base_uri' => 'http://172.18.0.5:9000']);  

        $nurseFirstname = htmlspecialchars($request->request->get('nurseFirstname'));
        $nurseLastname = htmlspecialchars($request->request->get('nurseLastname'));
        $nursePhone = htmlspecialchars($request->request->get('nursePhoneNumber'));
        $nursePostalCode = htmlspecialchars($request->request->get('nursePostalCode'));
        $nurseCity = htmlspecialchars($request->request->get('nurseCity'));

        $response = $client->request('POST', 'partner/pros/', [
            'form_params' => [
                'name' => $nurseFirstname . ' ' . $nurseLastname, 
                'city' => $nurseCity,  
                'phone' => $nursePhone,
                'zipcode' => $nursePostalCode,
                'job' => 1
                ]
                ]);


        try {
            if($response->getStatusCode() === 200 || $response->getStatusCode() === 204){
                $nurses = $response->getBody();

                $ret = array(
                    'nurses' => $nurses,
                    'status' => 200,
                );

                return new JsonResponse($nurses, 200, [], true);
            }
        } catch (\Exception $e) {
            $ret = array(
                'error' => $e->getMessage(),
            );


            return new JsonResponse($e, 500, [], true);
        }
    }  

вместо:

    /**
     * @POST("/partner/searchNurseToUser")
     */
    public function searchNurseAction(Request $request)
    {

        $client = new Client(['base_uri' => 'http://172.18.0.5:9000']);

        $nurseFirstname = htmlspecialchars($request->request->get('nurseFirstname'));
        $nurseLastname = htmlspecialchars($request->request->get('nurseLastname'));
        $nursePhone = htmlspecialchars($request->request->get('nursePhoneNumber'));
        $nursePostalCode = htmlspecialchars($request->request->get('nursePostalCode'));
        $nurseCity = htmlspecialchars($request->request->get('nurseCity'));

        $response = $client->request('POST', 'partner/pros/', [
            'form_params' => [
                'name' => $nurseFirstname . ' ' . $nurseLastname, 
                'city' => $nurseCity,  
                'phone' => $nursePhone,
                'zipcode' => $nursePostalCode,
                'job' => 1
                ]
                ]);

        try {
            if($response->getStatusCode() === 200 || $response->getStatusCode() === 204){
                $nurses = $response->getBody();

                $ret = array(
                    'nurses' => $nurses,
                    'status' => 200,
                );

                $view = $this->view($ret);

            }
        } catch (\Exception $e) {
            $ret = array(
                'error' => $e->getMessage(),
            );

            $view = $this->view($ret, 500);

        }

        return $this->handleView($view);
    }

Извините, мой вопрос не было завершено. Спасибо тебе

...