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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44365577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:16:12  来源:igfitidea点击:

Proxy in package.json not affecting fetch request

node.jsapireactjsproxyrequest

提问by Radoslav Naidenov

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

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

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

我正在运行客户端localhost:3001和后端port 3000

The fetch request :

获取请求:

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

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

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

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

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

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

Here is my package.json file:

这是我的package.json 文件

enter image description here

在此处输入图片说明

.. and the webpack.config: enter image description here

.. 和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.

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

采纳答案by Shubham Khatri

You can modify your fetch request API url to give the complete hostname since

您可以修改您的 fetch request API url 以提供完整的主机名,因为

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

also make sure that you have CORSenabled on your backend

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

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

如果你想通过重定向的WebPack,你可以尝试devServer.proxy

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

回答by Canis

I know I'm a little late to the game here, but I'll leave it here for future reference.

我知道我在这里玩游戏有点晚了,但我会把它留在这里以供将来参考。

To make the devServer proxy work as expected, you need to specify the HTTP Accepts header to be something else than "text/html". Do this with the init-object that fetch accepts as the second argument. A simple example:

要使 devServer 代理按预期工作,您需要将 HTTP Accepts 标头指定为“text/html”以外的其他内容。使用 fetch 接受作为第二个参数的 init-object 来执行此操作。一个简单的例子:

fetch("/api/profile",{
    headers:{
        "accepts":"application/json"
    }
})
.then(res => {
    console.log(res);
    return res.json();
})
.then(json => console.log(json) )
.catch( a => { console.log(a) });

The reason for this is that the WebPack Dev Server normally uses a context/namespace to differentiate between what to serve and what to forward. The create-react-app scripts do not extract a namespace from the proxy path in the package.jsonfile. Instead the scripts has the opinionated default behaviour that any request using something else than HTTP GET will get forwarded. Also, anything using HTTP GET, but NOT text/htmlas the Acceptsheader will get forwarded.

这样做的原因是 WebPack Dev Server 通常使用上下文/命名空间来区分要提供的内容和要转发的内容。create-react-app 脚本不会从package.json文件中的代理路径中提取命名空间。相反,脚本具有自以为是的默认行为,即使用 HTTP GET 以外的任何请求都将被转发。此外,任何使用 HTTP GET 但不是text/html作为Accepts标头的内容都将被转发。

The reasoning is because most React Apps are SPA (Single Page Applications) which use AJAX/Fetch to communicate with some API. API's normally use JSON or XML, but not text/html.

原因是大多数 React 应用程序都是 SPA(单页应用程序),它们使用 AJAX/Fetch 与某些 API 进行通信。API 通常使用 JSON 或 XML,但不使用text/html.

回答by Jose Pinheiro

In the package.json

在 package.json 中

"proxy": {
    "/api/users": {
        "target": "http://localhost:3000"
    }
},

回答by manna

The solution by user jellyfish-tom in https://github.com/webpack/webpack-dev-server/issues/793#issuecomment-316650146worked for me.

用户 jellyfish-tom 在https://github.com/webpack/webpack-dev-server/issues/793#issuecomment-316650146 中的解决方案对我有用。

devServer: {
  proxy: {
    "*": "http://[::1]:8081"
    // "secure": false,
    // "changeOrigin": true
  }
},

回答by Jonny Buchanan

Webpack Dev Server uses devServer.proxyconfigin your Webpack config to control proxying requests.

的WebPack开发服务器使用devServer.proxy的配置在你的WebPack配置来控制请求代理。