abdelrahmannasser
abdelrahmannasser

Reputation: 31

Proxy property isn't working in package.json

I'm new to react, I'm trying to make post request to an API endpoint. I sat the proxy in package.json to the endpoint url and here is the fetch function:

const requestOptions = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    username: username,
    password: password,
  }),
};

const res = await fetch("/token", requestOptions);

and here is my proxy prop: "proxy": "https://somedomain/api/auth"

when I do console.log(res.url), It always print "http://localhost:3000/api/auth/token/" not "https://somedomain/api/auth/token/"

why is that ?

And is there any solution ?

Upvotes: 1

Views: 200

Answers (1)

mappie
mappie

Reputation: 502

You need to add the Accept header, which is currently missing. Headers would look as follows:

headers: {
  "Content-Type": "application/json",
  "Accept": "application/json"
}

Other ways to proxy

  1. You can download the http-proxy-middleware package and configure your proxy.
  2. You could use webpack proxy and send your request to a different end server.
module.exports = {
  devServer: {
    proxy: {
      '/api': 'http://localhost:3000'
    }
  }
};

NOTE: Keep in mind the CORS issues would pop up so add Access-Control-Allow-Origin header as well.

Upvotes: 1

Related Questions