package.json 中的代理不影响获取请求 [英] Proxy in package.json not affecting fetch request

查看:47
本文介绍了package.json 中的代理不影响获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to fetch some data from the development server using React.

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

I am running the client on localhost:3001 and the backend on port 3000.

获取请求:

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

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

When I run my development server and webpack-dev-server I get the following output:

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

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

I tried specifying the proxy in the package.json so it would proxy the request to the API server, however nothing has changed.

这是我的 package.json 文件:

.. 和 webpack.config :

如果您需要从我的项目中查看任何其他内容,请告诉我.我很抱歉,如果我遗漏了一些东西并且没有做到彻底,我对使用这些技术还是很陌生.

Please tell me, if you need to see anything else from my project. I apologies, if I'm missing something and not being thorough, I'm still quite new to using these technologies.

推荐答案

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

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

also make sure that you have CORS enabled on your backend

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

In case your want to redirect through webpack, your can try devServer.proxy as

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

这篇关于package.json 中的代理不影响获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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