如何连接到本地主机中的两个不同的 Web 服务器
How To Connect to two different web server in localhost
我正在尝试使用 React 构建我的网站。
我正在使用 webpack-dev-server 为位于 localhost:8080 的 React 网站提供服务。
我在 localhost:9000 中有另一个服务器 运行,它有我们网站的 api。
但是当我尝试向 localhost:9000 发出获取请求以获取数据时,我遇到了以下错误。
您的提取操作出现问题:无法在 'Window' 上执行 'fetch':“http://127.0.0.1:9000' should be same as 'http://localhost:8080”的来源
我该如何解决?
听起来浏览器正在阻止对 API 的请求,因为主机不同 - 这是由 CORS headers which the API can send to say "these are the hosts which are allowed to make requests". You can turn off this checking by using a wildcard - as described in this gist here
控制的
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
if request.method == 'OPTIONS':
response.headers['Access-Control-Allow-Methods'] = 'DELETE, GET, POST, PUT'
headers = request.headers.get('Access-Control-Request-Headers')
if headers:
response.headers['Access-Control-Allow-Headers'] = headers
return response
app.after_request(add_cors_headers)
我正在尝试使用 React 构建我的网站。
我正在使用 webpack-dev-server 为位于 localhost:8080 的 React 网站提供服务。
我在 localhost:9000 中有另一个服务器 运行,它有我们网站的 api。
但是当我尝试向 localhost:9000 发出获取请求以获取数据时,我遇到了以下错误。
您的提取操作出现问题:无法在 'Window' 上执行 'fetch':“http://127.0.0.1:9000' should be same as 'http://localhost:8080”的来源
我该如何解决?
听起来浏览器正在阻止对 API 的请求,因为主机不同 - 这是由 CORS headers which the API can send to say "these are the hosts which are allowed to make requests". You can turn off this checking by using a wildcard - as described in this gist here
控制的def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
if request.method == 'OPTIONS':
response.headers['Access-Control-Allow-Methods'] = 'DELETE, GET, POST, PUT'
headers = request.headers.get('Access-Control-Request-Headers')
if headers:
response.headers['Access-Control-Allow-Headers'] = headers
return response
app.after_request(add_cors_headers)