Axios call api with GET become OPTIONS

て烟熏妆下的殇ゞ 提交于 2019-12-01 02:36:18

问题


I use axios for calling API (in front-end). I use the method "GET" :

import axios from 'axios';
import querystring from 'querystring';

var url   = "mydomain.local",
    token = "blablabla...blabla";  

var configs = {
    headers: {
        'Authorization': 'Bearer ' + token,
        'Agency': 'demo0'
    }
};

var testapi = axios.create({
        baseURL: 'http://api.' + url
    });

testapi.get( '/relativeUrl', configs
).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

I got a 405 Method Not Allowed. The method is "OPTIONS" but I use the method ".get()". 405 Method Not Allowed. Method OPTIONS

I test call api with postman and I get 200 OK :

postman 200 OK screenshot

Anyone has an idea ?


回答1:


Like @Shilly says, OPTIONS method is pre-flight on modern browsers when Preflighted requests conditions (MDN) :

In the response header I had Allow:"GET, HEAD, POST, PUT, DELETE". So OPTIONS method is not available and need to configure it on in the server (Apache).

I do the change on apache (/etc/apache2/sites-available/000-default.conf) :

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

In Request headers I have :

Origin: "null" is a problem. The cause is :

file:// URLs produce a null Origin which can't be authorized via echo-back. Don't trying to perform a CORS request from a file:// URL (see this post for more details)

After put my javascript file on a apache server, the Origin was not null but I need to add NelmioCorsBundle to my Symfony project to allow preflight




回答2:


So the way to solve this npm install qs.

Then:

import qs from 'qs'

function send(params) {
  return axios.post('/api/create/', qs.stringify(params))
}


来源:https://stackoverflow.com/questions/42137354/axios-call-api-with-get-become-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!