在axios中设置Content-Type标头会导致不发送任何数据

时间:2017-11-09 14:54:20

标签: javascript ajax post axios

我使用axios将数据发布到WebApi,我尝试将Content-Type设置为application / json,但是当我向配置添加标头时,没有发送数据。 我的axios请求:

axios({
    method: 'post',
    headers: {'Content-Type': 'application/json',},
    url: `${URL}/Signin`,
    data: user  
});

,结果请求:

OPTIONS http://localhost:50644/api/Signin HTTP/1.1
Host: localhost:50644
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:3000/Signin
Accept-Encoding: gzip, deflate, br
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4

当我从axios请求中删除标题时,一切正常,但内容类型错误。

POST http://localhost:50644/api/Signin HTTP/1.1
Host: localhost:50644
Connection: keep-alive
Content-Length: 40
Accept: application/json, text/plain, */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:3000/Signin
Accept-Encoding: gzip, deflate, br
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
{
    "Name": "test",
    "Password": "test"
}

我做错了什么?提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我无法确定data: JSON.stringify(user)的数据结构是什么样的,但我想你需要userinitialize转换为JSON格式。