Background In daily development, when we need to communicate with the backend, when sending interface request, the backend will check whether the interface has cookie, if not, the backend will return a redirectUrl, which is a login address on the line. Therefore, the common practice is to log in to the online system, copy the cookie, write the cookie of the local Webpack, and restart the Webpack again.
{
/api/: {
headers: {
cookie: 'Cookie from the line I just logged in to'}}}Copy the code
Problems arising
- Currently debugged
cookie
If it fails, you need to log in again and then copycookie
And finally restart the whole project - Every time you commit code, you need to clean it up
cookie
【 becausecookie
It’s different every time. - A lot of time was spent on this replication
cookie
on
Cause analysis,
- The backend needs to make interface calls every time
cookie
check cookie
failureredirectUrl
It’s an online address written dead, not based onrefere
To determine the
Project research
cookie
Do not do failure checkredirectUrl
According to therefere
To judge- Front end by
webpack
The proxy implementationcookie
Auto write back
The results of
cookie
andredirectUrl
These two solutions, for the back end of the change is very large, so it will not work- use
webpack
Automatic back to write
let cookie = ' '; . {/api/: {
// This means that you want to customize the data returned
selfHandleResponse: true.onProxyReq(proxyReq, req, res) {
// Set cookies before each request
proxyReq.setHeader('cookie', cookie);
},
onProxyRes(proxyRes, req, res) {
if (proxyRes.headers['set-cookie']) {
// Get the cookie returned by the backend system
cookie = proxyRes.headers['set-cookie'].join('; ');
}
var body = [];
proxyRes.on('data'.function (chunk) {
body.push(chunk);
});
proxyRes.on('end'.function () {
body = JSON.parse(Buffer.concat(body).toString());
if(! body.success && body.code ===302) {
body.message.redirect = 'http://localhost:3000';
}
res.end(Buffer.from(JSON.stringify(body))); }); }}}...Copy the code
This approach is discussed only for point-to-point systems
This scheme will be ineffective if the following system is used
So how do you solve this?