gpt4 book ai didi

javascript - 如何添加跨域资源共享请求头?

转载 作者:行者123 更新时间:2023-12-03 01:05:17 25 4
gpt4 key购买 nike

我正在使用 React JS 构建一个 REST 消费者,我已经构建了一个 REST api 作为后端服务,前端将是一个完全不同的应用程序。将前端与后端分离。

我目前正在努力解决的是从前端到后端的跨源请求。后端托管在 http://localhost:8080 前端 React 应用程序托管在 http://localhost:3000 。发出请求时,我在控制台上收到以下错误:

Failed to load http://localhost:8080/api/something: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

现在我已经使用 chrome 扩展修复了此错误以允许 CORS:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

但这只是一个临时解决方案,我尝试添加 Access-Control-Allow-Origin标题,但这似乎不起作用。

这是我用来发出请求的代码:

let Myheaders = new Headers()
Myheaders.append("Access-Control-Allow-Origin", "http://localhost:8080/")

let res = await fetch("http://localhost:8080/api/something",
{
method: "get",
mode: "cors",
headers: Myheaders
})
let res1 = await res.json()

我尝试为带有反斜杠或不带反斜杠Access-Control-Allow-Origin header 添加多个值,但似乎没有任何效果工作。

有人遇到同样的问题并有解决方案吗?

最佳答案

这是后端问题而不是前端问题您应该允许来自后端的 cors,这取决于后端使用的技术

关于javascript - 如何添加跨域资源共享请求头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52438604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com