0
votes

I'm using axios to POST data to WebApi and I'm trying to set Content-Type to application/json, but when I'm adding headers to config no data is sent. My axios request:

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

and it results with request:

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

When I remove headers from my axios request all is ok, but Content Type is wrong.

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"
}

What I'm doing wrong? Thank you in advance for your help!

1
Your first request is a CORS preflight check (OPTIONS). Your second is a POST. - serpent5
But my browser dosen't make second request. The response I get from server is: {Message: "The origin 'http://localhost:3000' is not allowed."} - Koli96
Which likely means your OPTIONS preflight check is failing and your server does not support CORS. This is a CORS issue - there are tonnnes of helpful answers here on SO to help you with that. - serpent5
My server is .NET Web API, and I have CORS configured: Access-Control-Allow-Origin: * Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS - Koli96
Please include the entire HTTP response to your OPTIONS request. - serpent5

1 Answers

0
votes

I can't be sure without knowing what the data structure of user looks like, but I imagine you need to do data: JSON.stringify(user) to turn user into JSON format.