I am trying to use proxy to update the base url and also append the token from the local storage. I am able to update the URL but when I try to access the token it gives me error
ReferenceError: window is not defined
. Is it possible to access local storage from proxy. I tried localstorage.getItem('token')
and also windows.localstorage.getItem('token')
.
My proxy.conf.js
file looks like this
const PROXY_CONF = [
{
context: ['/testData/*'],
target: 'https://test.com/',
secure: false,
changeOrigin: true,
bypass: function (req, res, proxyOptions) {
req.headers['authorization'] = typeof window !== 'undefined' ? window.localStorage.getItem(`token`) : '';
},
}
];
module.exports = PROXY_CONF;
CodePudding user response:
Proxy.config.js is a configuration used by webpack internally. It doesn't have any knowledge about the browser. This server is ONLY used for development purposes and you won't deploy/use this guy in an actual prod environment.
If you want to add a bearer token (or any other kind of tokens) to your requests you'll have to create an interceptor. Here's a link to a tutorial