node.js - package.json 中的代理不影响获取请求

标签 node.js reactjs api proxy create-react-app

我正在尝试使用 React 从开发服务器获取一些数据。

我在 localhost:3001 上运行客户端,在 port 3000 上运行后端。

获取请求:

 const users = fetch('/api/users');
    users.then((err,res) => {
      console.log(res);
    })

当我运行我的开发服务器和 webpack-dev-server 时,我得到以下输出:

GET http://localhost:3001/api/users 404 (Not Found)

我尝试在 package.json 中指定代理,以便它将请求代理到 API 服务器,但是没有任何改变。

这是我的 package.json 文件:

enter image description here

.. 和 webpack.config : enter image description here

如果您需要查看我的项目中的其他内容,请告诉我。很抱歉,如果我遗漏了什么并且不够彻底,我对使用这些技术还是很陌生。

最佳答案

您可以修改您的获取请求 API url 以提供完整的主机名,因为

 fetch('http://localhost:3000/api/users') 

还要确保您在后端启用了 CORS

如果你想通过 webpack 重定向,你可以试试 devServer.proxy as

devServer: { 
    inline: true, 
    contentBase: './dist', 
    port: 3001, 
    proxy: { "/api/**": { target: 'http://localhost:3000', secure: false }  }
 }

关于node.js - package.json 中的代理不影响获取请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44365577/

相关文章:

node.js - 编译 Node 模块时 typescript 错误

node.js - 如何从express.js中的另一个函数调用一个函数?

javascript - Cypress 测试 Material-UI 日期选择器不适用于 Github 操作

javascript - 如何使用 Flow 在 React 中添加多态属性

api - 在Youtube API中进行词组搜索

javascript - 如何识别以下代码模式

javascript - 不能使用命名空间 'Boom' 作为类型

javascript - 类型 IntrinsicAttributes 和字符串 [] 上不存在属性 'props'

api - 在ASP Net Core API中使用NLog进行Elasticsearch日志记录失败

php - Google AdWords PHP客户端库v201702