6

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.

Mauro Sala
  • 1,166
  • 2
  • 12
  • 33

4 Answers4

5
axios({
    url: 'http://127.0.0.1/myapi/test.php',
    method: 'get',
    headers: {
        'X-Id-Token': 'abc123abc123',
        'Content-Type': 'application/json'
    }
 })
 .then(response => {
    console.log(response)
 }) 
 .catch(err => {
    console.log(err);
 });
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • I guess the problem with the header key "X-Id-Token" you are sending. May be API expecting some other key name instead of "X-Id-Token". Try using "token" or authorization: `Bearer ${token}`. – Shiladitya Jun 30 '17 at 14:47
  • No, I have tried to send the header key "pippo" but the problem is the same – Mauro Sala Jun 30 '17 at 14:49
0

Check out axios interceptors for a more general solution to what you have here. It allows you to run a function each time a request is made, meaning that you can move your headers config into a global function that gets called for any request.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
Chase DeAnda
  • 15,963
  • 3
  • 30
  • 41
0

@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.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Adnan Ahmad
  • 848
  • 1
  • 13
  • 12
-2

good suggestion from Mayank Shukla, it's a CORS problem, I modified my web.config from this

<add name="Access-Control-Allow-Origin" value="*" />

to this

<add name="Access-Control-Allow-Origin" value="http://localhost:3000" />
Mauro Sala
  • 1,166
  • 2
  • 12
  • 33