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

查看:144
本文介绍了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 laina = fetch('/api/users');
    laina.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作为

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天全站免登陆