Axios 使用 GET 调用 api 成为 OPTIONS [英] Axios call api with GET become OPTIONS

查看:33
本文介绍了Axios 使用 GET 调用 api 成为 OPTIONS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 axios 调用 API(在前端).我使用方法GET":

从'axios'导入axios;从查询字符串"导入查询字符串;var url = "mydomain.local",token = "blablabla...blabla";变量配置 = {标题:{'授权':'承载'+令牌,'代理':'演示0'}};var testapi = axios.create({baseURL: 'http://api.'+ 网址});testapi.get('/relativeUrl', configs).then(函数(响应){控制台日志(响应);}).catch(函数(错误){控制台日志(错误);});

我收到了不允许的 405 方法".方法是OPTIONS",但我使用方法.get()".

起源:空"是一个问题.原因是:

<块引用>

file://URLs 产生一个无法通过授权的空源回声.不要尝试从 file://URL 执行 CORS 请求(查看此帖子了解更多详情)

将我的 javascript 文件放在 apache 服务器上后,Origin 不为空,但我需要将 NelmioCorsBundle 添加到我的 Symfony 项目以允许预检

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 ?

解决方案

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

这篇关于Axios 使用 GET 调用 api 成为 OPTIONS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆