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 发出 get 请求.
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屋!