提取API不适用于localhost / 127.0.0.1 [英] Fetch API not working with localhost/127.0.0.1

查看:151
本文介绍了提取API不适用于localhost / 127.0.0.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅作为背景,我有一个React应用程序坐在远程EC2 Ubuntu实例上。同一台服务器还运行一个Go应用程序,监听端口8080(已从安全性设置向所有人开放该端口)。

Just as background, I have a react app sitting on a remote EC2 Ubuntu instance. The same server also runs a Go app listening on port 8080 (port has been opened to everyone from the Security settings).

我正在尝试使用Fetch API发出请求,从React应用程序中获取,如下所示:

I am trying to make a request with Fetch API, from the React app, as follows:

var bearer = 'Bearer ...'
return fetch('http://localhost:8080/home', {
  headers: new Headers({
    'Authorization': bearer
  })
})

在控制台中,无论是Chrome还是Firefox,我都会得到:

In the console, from both Chrome and Firefox, I am getting:

TypeError:尝试获取资源时出现网络错误

当我替换 localhost 与 127.0.0.1

但是,使用EC2实例的外部IP可行(并触发CORS请求-由于 Authorization标头-由服务器顺利处理)。

Using the external IP of the EC2 instance, however, works (and triggers a CORS request - due to the 'Authorization' header - which is handled smoothly by the server).

在后一种情况下,我还可以看到服务器记录了传入请求对于OPTIONS和GET(在前一种情况,两种方法都没有日志。)

In the latter case, I can also see the server logging the incoming request for both OPTIONS and GET (in the former case, no logs are present for either method).

我还尝试了从EC2计算机到 localhost 并有效地处理了请求,这使我认为使用Fetch API根本不会触发该请求。

I also tried CURL'ing from the EC2 machine to localhost and the request effectively goes through which leads me to think that with the Fetch API the request is not triggered at all.

任何建议都将不胜感激。如果我做错了什么,请指出正确的方向。

Any advice would be appreciated. If I am doing anything wrong please point me in the right direction.

推荐答案

编写 localhost 会调用您的(localhost)计算机(存在浏览器),因为 js 代码正在您的浏览器中运行。

When you write localhost it calls your (localhost) machine (on which the browser is present) because the js code is running in your browser.

您应该为您的API端点创建一个域/子域,并使用它代替localhost或继续使用硬编码的IP地址。

You should create a domain/sub-domain for your API endpoint and use it instead of localhost or continue to use the hard-coded IP address.

您还应该仅在允许的后端来源中允许您的前端网站域。例如您的网站可以是 www.example.com ,后端网址可以是 www.api.example.com 。您应该只允许 www.example.com 作为来源,可以通过 www进行投放.api.example.com 。您需要在后端进行配置。

You should also allow only your frontend website domain in the allowed origins for your backend. Ex. your website can be www.example.com and backend url can be www.api.example.com. You should allow only www.example.com as the origin which can be served through www.api.example.com. You will need to configure this in the backend.

这篇关于提取API不适用于localhost / 127.0.0.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆