使用axios发送帖子formData无效,但是使用请求

时间:2020-03-27 19:07:25

标签: node.js axios node-request

由于请求已过时,我正尝试从request迁移到axios
假设url'https://www.example.com'收到带有包含登录信息的formdata的发布请求,并在成功时打印'Logged in',否则输出'Cannot login'(出于隐私原因,我无法共享url) 。
我有以下代码,该代码使用axios并显示“无法登录”:

axios = require('axios')
FormData = require('form-data')
form = new FormData()
form.append('email', 'example@gmail.com')
form.append('password', '1234')
axios({
    method: 'post',
    url: 'https://www.example.com',
    data: form
}).then(function (response) {
    console.log(response['data']); // Prints "Could not log in"
}).catch(function (error) {
    console.log(error);
})

我还有以下代码,该代码使用请求并显示“已登录”:

request = require('request')
request.post({
    url: 'https://www.example.com',
    method: 'POST',
    formData: {
        'email': 'example@gmail.com',
        'password': '1234'
    }
}, function(error, response, body) {
    console.log(body); // Prints "Logged in"
})

为什么该操作使用请求而不是axios工作?

1 个答案:

答案 0 :(得分:1)

以下是请求代码的输出:

content-length: 288
content-type: multipart/form-data; boundary=--------------------------539399892261259576142530

----------------------------539399892261259576142530
Content-Disposition: form-data; name="email"

example@gmail.com
----------------------------539399892261259576142530
Content-Disposition: form-data; name="password"

1234
----------------------------539399892261259576142530--

这是Axios代码的输出:

content-length: 288",
accept: application/json, text/plain, */*
content-type: application/x-www-form-urlencoded
user-agent: "axios/0.19.2

----------------------------076596858609798080293678
Content-Disposition: form-data; name="email"

example@gmail.com
----------------------------076596858609798080293678
Content-Disposition: form-data; name="password"

1234
----------------------------076596858609798080293678--

尝试在Axios中添加此选项:headers: {'Content-Type': `multipart/form-data; boundary=${form._boundary}` }