Most of time this is not useful for developers who can control the backend API server. My use case is when the backend API server is not controlled by myself and while developing frontend flutter apps(web, ios and android), server didn't set up proper cookie header so my local flutter web cannot handle the cookie-based auth.
- API Server on http://yourapi.server that you cannot change http response headers
- We open a proxy https server on https://localhost:8083
- On flutter web, remember to add
withCredentials=true
such as for dio clientdio.options.extra['withCredentials'] = true;
index.js
var https = require('https'),
httpProxy = require('http-proxy'),
fs = require('fs');
var proxy = httpProxy.createProxyServer({});
proxy.on('proxyReq', function (proxyReq, req, res, options) {
proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});
proxy.on('proxyRes', function (proxyRes, req, res, options) {
console.log(`$proxyRes`, JSON.stringify(proxyRes.headers));
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
res.setHeader(
'Access-Control-Allow-Methods',
'GET,POST,PUT,HEAD,DELETE,OPTIONS',
);
res.setHeader(
'Access-Control-Allow-Headers',
'content-Type,x-requested-with',
);
res.setHeader('Access-Control-Allow-Credentials', 'true');
if (proxyRes.headers['set-cookie']) {
if (/sf_redirect/gi.test(proxyRes.headers['set-cookie'][0])) {
proxyRes.headers['set-cookie'][0] = '';
} else {
proxyRes.headers['set-cookie'][0] =
proxyRes.headers['set-cookie'][0] + '; Secure; SameSite=None';
}
res.setHeader('set-cookie', proxyRes.headers['set-cookie']);
}
// console.log();
// proxyRes.setHeader('X-Special-Proxy-Header', 'foobar');
});
var server = https.createServer(
{
key: fs.readFileSync('.cert/localhost.key'),
cert: fs.readFileSync('.cert/localhost.cert'),
},
function (req, res) {
console.log('on request');
// You can define here your custom logic to handle the request
// and then proxy the request.
proxy.web(req, res, {
target: 'http://your/',
});
proxy.on('error', function (e) {
console.error(e);
});
},
);
const PORT = 8083;
server.listen(PORT, () => {
console.log(`listening on port ${PORT}`);
});
package.json
"dependencies": {
"http-proxy": "^1.18.1"
}
- $ npm install -g devcert-cli
- $ devcert generate localhost
- $ mv ./localhost.cert ./.cert/localhost.cert && mv ./localhost.key ./.cert/localhost.key
- $ HTTPS=true SSL_CRT_FILE=./.cert/localhost.cert SSL_KEY_FILE=./.cert/localhost.key HOST=0.0.0.0 npm start
- then will see green lock