使用 React 从 nodejs 服务器获取图像

时间:2021-01-06 15:14:51

标签: node.js reactjs nginx centos

我遇到了一个问题,我只能通过我的外部 ip 从 nodejs 检索图像文件

这是唯一有效的方法 src={`http://<outside ip>:5000/${<img>}`}

我尝试了这些变体来修复它:(为简单起见缩写)

/api/<img>    (the /api/ route is used by nginx to route to nodejs)
localhost:5000/<img>
http://localhost:5000/<img>
http://localhost:5000/api/<img>
http://0.0.0.0:5000/<img>
http://0.0.0.0:5000/api/<img>
http://127.0.0.1:5000/<img>
http://127.0.0.1:5000/api/<img>
http://api/<img>   

我的问题是我必须向外界公开端口 5000 才能使其正常工作

我不明白为什么本地主机版本都没有拉取镜像。尽管安全性令人担忧,但速度似乎也受到了巨大打击。

这是 nginx 的问题吗? Centos的问题?不允许本地主机发送数据?还是我做错了?

TYIA

1 个答案:

答案 0 :(得分:0)

没有看到您的代码很难说,但这可能是一个 CORS 问题吗?

如果您使用 express 作为节点服务,那么您可以在此处查看如何轻松配置 CORS:https://expressjs.com/en/resources/middleware/cors.html

如果您使用 React 中的 fetch 来检索数据,您还可以尝试使用 "mode": "no-cors" 选项进行传递,如下所示:

fetch('http://localhost:5000/api/<img>', {
  method: 'GET',
  mode: 'no-cors', 
}).then(result => {
  // Do whatever you need to do 
}).catch(err => {
  // Handle error
})