Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

node.js - Proxy in package.json not affecting fetch request

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

I am running the client on localhost:3001 and the backend on 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:

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.

Here is my package.json file:

enter image description here

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

also make sure that you have CORS enabled on your backend

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 }  }
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...