Proxy in package .json does not affect fetch request

I am trying to get some data from a development server using React.

I work with the client in localhost:3001

, and the server side in port 3000

.

Request to receive:

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

      

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

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

      

I tried to specify a proxy in package.json so that it would pass the request to the API server, but nothing changed.

Here is my package.json file :

enter image description here

.. and webpack.config : enter image description here

Please tell me if you need to see something else from my project. I am sorry if I missed something and was not thorough, I am still quite new to these technologies.

+10


source to share


4 answers


You can change the get request API url with the fully qualified hostname, as

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

      

also make sure you have enabled CORS

on your backend



If you want to redirect via webpack you can try devServer.proxy

like

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

      

+11


source


In package.json



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

      

+2


source


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

For the devServer proxy to work properly, you must specify an HTTP Accepts header other than "text / html". Do this with an init object, which fetch takes as its second argument. 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 usually uses a context / namespace to differentiate between what to serve and what to send. The create-react-application scripts do not extract the namespace from the proxy path in the file package.json

. Instead, scripts have a default, overconfident behavior that any request other than HTTP GET will be redirected. Also, anything that uses HTTP GET but NOT text/html

as a header Accepts

will be redirected.

The reason is that most React apps are SPA (Single Page Apps) that use AJAX / Fetch to interact with some APIs. APIs usually use JSON or XML, but not text/html

.

+2


source


Webpack Dev Server uses devServer.proxy

config
in your Webpack config to control proxy requests.

0


source







All Articles