Post form data with axios in Node.js

后端 未结 4 1935
一个人的身影
一个人的身影 2021-02-18 15:39

I\'m testing out the Uber API on Postman, and I\'m able to send a request with form data successfully. When I try to translate this request using Node.js and the axios library I

4条回答
  •  深忆病人
    2021-02-18 16:03

    It is not true! You can post data with axios using nodejs. I have done it. The problem is, if you use PHP on the server side, there is a pitfall you need to be aware of. Axios posts data in JSON format (Content-Type: application/json) PHP's standard $_POST array is not populated when this content type is used. So it will always be empty. In order to get post parameters sent via a json request, you need to use file_get_contents("http://php://input") .

    A simple PHP script on the server side would be:

    if($_SERVER['REQUEST_METHOD']==='POST' && empty($_POST)) {
     $_POST = json_decode(file_get_contents('http://php://input'));
    }
    

    Using this method you can avoid the formData dependency. You CAN post data directly from node.js.

提交回复
热议问题