reactjs axios get request with custom header

Viewed 21160

I need to do this call

axios.get("http://127.0.0.1/myapi/test.php").then((response) => {
})

If I do this call all is ok and HTTP method is GET, but if I change to this

var config = {
    headers: {"X-Id-Token": "abc123abc123"}
};
axios.get("http://127.0.0.1/myapi/test.php", config).then((response) => {
})

The HTTP method is OPTIONS and the call fails, why?

EDIT

I'm runnig reactjs project with node (localhost:3000) and I call php api on IIS (http://127.0.0.1/myapi)

SOLUTION

Axios client makes a "ping" request for to check if address is reachable. So, the first call is in OPTIONS method, later calls are in GET.

4 Answers

@Mauro Sala Your axios request is correct. You need to allow your custom headers on server side. If you have your api in php then this code will work for you.

header("Access-Control-Allow-Origin: *");   
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, X-Id-Token");

Once you will allow your custom headers on server side, your axios requests will start working fine.

Related