简体   繁体   English

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

[英]Proxy in package.json not affecting fetch request

I am trying to fetch some data from the development server using React.我正在尝试使用 React 从开发服务器获取一些数据。

I am running the client on localhost:3001 and the backend on port 3000 .我在localhost:3001上运行客户端,在port 3000上运行后端。

The fetch request :获取请求:

 const users = fetch('/api/users');
    users.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.json so it would proxy the request to the API server, however nothing has changed.我尝试在package.json中指定代理,以便将请求代理到 API 服务器,但是没有任何改变。

Here is my package.json file :这是我的package.json 文件

在此处输入图像描述

.. and the webpack.config : .. 和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.很抱歉,如果我遗漏了一些东西并且不够彻底,那么我对使用这些技术还是很陌生。

You can modify your fetch request API url to give the complete hostname since您可以修改获取请求 API url 以提供完整的主机名,因为

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

also make sure that you have CORS enabled on your backend还要确保您在后端启用了CORS

In case your want to redirect through webpack, your can try devServer.proxy as如果你想通过 webpack 重定向,你可以试试devServer.proxy

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

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".要使 devServer 代理按预期工作,您需要将 HTTP Accepts 标头指定为“text/html”以外的其他内容。 Do this with the init-object that fetch accepts as the second argument.使用 fetch 接受的 init-object 作为第二个参数执行此操作。 A simple example:一个简单的例子:

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.这样做的原因是 WebPack 开发服务器通常使用上下文/命名空间来区分要服务的内容和转发的内容。 The create-react-app scripts do not extract a namespace from the proxy path in the package.json file. create-react-app 脚本不会从package.json文件中的代理路径中提取命名空间。 Instead the scripts has the opinionated default behaviour that any request using something else than HTTP GET will get forwarded.相反,脚本具有自以为是的默认行为,即任何使用 HTTP GET 以外的东西的请求都将被转发。 Also, anything using HTTP GET, but NOT text/html as the Accepts header will get forwarded.此外,任何使用 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.原因是大多数 React 应用程序都是 SPA(单页应用程序),它们使用 AJAX/Fetch 与某些 API 进行通信。 API's normally use JSON or XML, but not text/html . API 通常使用 JSON 或 XML,但不使用text/html

In the package.json在 package.json

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

The solution by user jellyfish-tom in https://github.com/webpack/webpack-dev-server/issues/793#issuecomment-316650146 worked for me.用户 jellyfish-tom 在https://github.com/webpack/webpack-dev-server/issues/793#issuecomment-316650146中的解决方案对我有用。

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

I had the same problem using axios and was only able to get it working by using the complete hostname and enabling Cors.我在使用 axios 时遇到了同样的问题,并且只能通过使用完整的主机名并启用 Cors 来使其工作。

const response = await axios.get('http://localhost/users/');

Install cors安装cors

npm i cors

Use cors使用cors

const express = require("express");
const request = require("request");
const cors = require("cors");
const app = express();

app.use(cors());

app.use("/", (req, res) => {
  //...
});

app.listen(80, () => {
  console.log("CORS-enabled web server listening on port 80");
});

Ref 参考

Webpack Dev Server 在你的 Webpack 配置中使用devServer.proxy配置来控制代理请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何仅在POST请求中在package.json中设置代理? - How to set up proxy in package.json for POST request only? 添加代理以反应 package.json 后,不断收到“代理错误:无法代理请求”错误 - Keep getting “Proxy error: Could not proxy request” error after adding proxy to react package.json package.json 中的代理集在方法:“post”添加到 fetch 时不起作用 - Proxy set in package.json not working when method: 'post' added to fetch 将 package.json 中的代理设置为 env 变量 - set proxy in package.json to env variable 前端 package.json 中的代理配置如何请求 void cors? - How does a proxy config in frontend package.json a void cors request? 不定义代理但得到“当在 package.json 中指定“代理”时”错误 - Define no proxy but get 'When “proxy” is specified in package.json' error npm仅获取package.json并将其转储到stdout - npm fetch just package.json of package and dump to stdout 在Windows上,package.json中的React Create App Proxy Agent在Windows上运行缓慢 - React create app proxy agent in package.json is slow on Windows 反应 | Package.Json | “代理”在 Google App Engine 中不起作用 - React | Package.Json | “proxy” Not Working in Google App Engine 反应,从package.json代理websocket获取本地计算机 - React, proxy to websocket from package.json get local machine
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM