[英]Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response
--It was a host error. --这是主机错误。 Issue is solved--
问题解决了——
I am using express API.我正在使用快速 API。
I have enabled all cors through npm cors
package.我已经通过 npm
cors
包启用了所有 cors。
like this app.use(cors())
像这个
app.use(cors())
It's working fine when I run it on localhost.当我在本地主机上运行它时,它工作正常。 It was also working fine on the actual VPS (server), but suddenly today my API started giving me this error:-
它在实际的 VPS(服务器)上也运行良好,但今天突然我的 API 开始给我这个错误:-
Access to XMLHttpRequest at 'https://apilink' from origin 'https://frontendlink' has been blocked by CORS policy: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response.
It's still working fine on my localhost, but now giving above error on actual website.它在我的本地主机上仍然可以正常工作,但现在在实际网站上出现上述错误。
Below are some of my code block下面是我的一些代码块
Thanks in advance提前致谢
My Axios Instance on frontend我在前端的 Axios 实例
import axios from "axios"
const axiosInstance = axios.create({
headers: {
Authentication: `Bearer ${
somewhere_token ?? null
}`,
},
})
export default axiosInstance
SomeWhere in server.js before all routes在所有路由之前的 server.js 中的某个位置
app.use(cors())
I have also tried below solutions in server.js file but none is fixing my issue我也在 server.js 文件中尝试了以下解决方案,但没有解决我的问题
// solution 1
app.options('*', cors());
// solution 2
app.use(cors({
origin: "*",
allowedHeaders: "*",
}))
Probably you can fix it by adding * everywhere, but please consider using a reverse proxy to make your request to backend proxy-passed from frontend host as the best practice.可能您可以通过在任何地方添加 * 来修复它,但请考虑使用反向代理将您的请求从前端主机传递到后端代理作为最佳实践。 I know it's an additional learning curve, but for modern APIs that's probably must have as it allows much more than just solving CORS issue.
我知道这是一个额外的学习曲线,但对于现代 API 来说,这可能是必须的,因为它不仅可以解决 CORS 问题。
Good guide here https://blogs.perficient.com/2021/02/10/nginx-proxy-for-cors/这里有很好的指南https://blogs.perficient.com/2021/02/10/nginx-proxy-for-cors/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.