Access-Control-Allow-Headers不允许请求标头字段X-CSRF-TOKEN [英] Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers
问题描述
我正在使用vue和axios发出对embed.rock的获取请求.
I'm making a get request to embed.rock using vue and axios.
axios({
method: 'get',
url: 'https://api.embed.rocks/api?url=' + this.url,
headers: {
'x-api-key': 'my-key'
}
})
当我使用CDN通过嵌入式脚本获取vue和axios时,我的代码可以正常工作,并且得到响应.
When I use a CDN to get vue and axios with an inline script my code works fine and I get a response back.
当我使用外部脚本引用已安装的vue和axios scrpts时,代码不再运行,并且出现以下错误:
When I reference the installed vue and axios scrpts with an external script the code no longer runs and I get the following error:
无法加载 https://api.embed.rocks/api?url=https://www.youtube.com/watch?v=DJ6PD_jBtU0&t=4s :不允许请求标头字段X-CSRF-TOKEN通过Access-Control-Allow-Headers在飞行前响应中.
Failed to load https://api.embed.rocks/api?url=https://www.youtube.com/watch?v=DJ6PD_jBtU0&t=4s: Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.
当我单击控制台中的错误时,它只会带我到:
When I click on the error in the console it just brings me to:
<!DOCTYPE html>
推荐答案
Laravel设置了全局配置,以自动将X-CSRF-TOKEN
包含在您的bootstrap.js
文件中的请求标头中.
Laravel is setting a global configuration to include automatically the X-CSRF-TOKEN
in the headers of the request in your bootstrap.js
file.
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
因此,如果要删除令牌,可以这样实现:
Therefore, if you want to remove the token, you can achieve it like this:
var instance = axios.create();
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
instance({
method: 'get',
url: 'https://api.embed.rocks/api?url=' + this.url,
headers: {
'x-api-key': 'my-key'
}
});
这篇关于Access-Control-Allow-Headers不允许请求标头字段X-CSRF-TOKEN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!