問題描述
我在靜態文件夾中有一個 json 文件,我正在嘗試從另一個網站訪問它,但我遇到了 CORS 問題.
I have a json file on static folder and I'm trying to access it from another web site, but I'm having problem with the CORS.
如何在靜態文件響應中添加標頭(如 Access-Control-Allow-Origin)?
How can I add headers (like Access-Control-Allow-Origin) on the static files response?
我試過這個 https://github.com/nuxt/nuxt.js/issues/2554#issuecomment-363795301,但不適用于靜態文件.
I tried this https://github.com/nuxt/nuxt.js/issues/2554#issuecomment-363795301, but didn't work for static files.
module.exports = function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
next()
}
推薦答案
Nuxt 有一個內置渲染屬性選項,您可以在 nuxt.config.js 文件中使用它.
Nuxt has a build in render property option, that you can use inside the nuxt.config.js file.
如果您想為靜態文件添加訪問控制標頭,只需使用 setHeaders
函數.
If you want to add Access-Control Headers for static files just use the setHeaders
function.
參見 https://nuxtjs.org/api/configuration-render#static.
在后臺 Nuxt 使用 serve-static 包(也適用于其他選項).
In the background Nuxt uses the serve-static package (also for other options).
例子:
render: {
static: {
setHeaders(res) {
res.setHeader('X-Frame-Options', 'ALLOWALL')
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET')
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
}
}
這篇關于如何在 Nuxt 靜態文件響應中添加標題?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!