首页 > 解决方案 > 使用 React 从 nodejs 服务器获取图像

问题描述

我有一个问题,我只能通过我的外部 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

标签: node.jsreactjsnginxcentos

解决方案


很难说没有看到你的代码,但这可能是一个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
})

推荐阅读