webpack-dev-server returns 504 while backend returns 204 - node.js

Here is an error text (app crashes at all 204 reponses):
[HPM] Error occurred while trying to proxy request /rest/profiles/change-password from site.loc:3005 to https://site.loc (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
Debugged backend response. It returns 204 status code with empty body (data = null). If I build an app everything is working fine. One more moment: it doesn't occur at other developer's MAC OS.
My webpack devServer config:
devServer: {
contentBase: PATHS.dist,
host: appDomain,
proxy: {
'/rest': {
target: appUrl,
secure: false,
changeOrigin: true
},
...
}
My enviroment:
Windows 10 Pro x64
node version: v12.18.4
webpack-dev-server: "^3.11.0",
Please, help!

I spent about 3 days on that error, myabe this answer could help anyone...
I didn't figure out why this error occur, good people helped me with this code:
proxy: {
'/rest': {
target: appUrl,
secure: false,
changeOrigin: true,
onProxyRes: function (proxyRes, req, res) {
console.log(proxyRes.statusCode);
},
onError: function (err, req, res) {
console.log(`req.body: ${req.body}`); // here it returned undefined
console.log(`err.code: ${err.code}`);
if (err.code === 'ECONNRESET') {
res.writeHead(204, {'Content-Type': 'application/json'});
res.end();
}
},
},
Previously tried to do this using webpack-dev-server bypass method, axios interceptors, but with no success.

Related

Vite forwad POST request to GET

Here is my vite config
server: {
host: "0.0.0.0",
proxy: {
"/api": {
target: "https://xxx.xxx.inc",
changeOrigin: true,
rewrite: (path) => {
return path.replace(/^\/api/, "");
},
secure: false,
},
},
},
When I post a data, weired things happend!
The POST was "301 Moved Permanently" And it became GET!
vite:proxy /api/core/login -> https://xxx.xxx.inc +0ms
vite:time 475.67ms /core/login +10s
vite:spa-fallback Not rewriting GET /core/login/ because the client prefers JSON. +10s
vite:time 0.73ms /core/login/ +7ms
vite:proxy /api/core/login -> https://xxx.xxx.inc +15m
vite:time 476.08ms /core/login +15m
vite:spa-fallback Not rewriting GET /core/login/ because the client prefers JSON. +15m
vite:time 0.66ms /core/login/ +5ms
For Proxy server,
A POST should be always POST after

http-proxy-middleware responseInterceptor - Error fetching proxied request: unexpected end of file

We're using the NodeJS http-proxy-middleware and the responseInterceptor (and customRouter), as below:
const options = {
target: ...,
router: ...,
changeOrigin: true,
secure: true,
key: ...,
cert: ...,
followRedirects: true,
selfHandleResponse: true,
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
return responseBuffer;
}) };
const myProxy = createProxyMiddleware(options);
const app = connect();
app.use(myProxy);
app.listen(portNumber);
The issue is we're getting an intermittent error. I can see from the request that this is on
"Error fetching proxied request: unexpected end of file"
in the JS file response-interceptor.js in the http-proxy-middleware module. From what I gather from the request, this error gets thrown on different files, so it's not just 204's with no content.
I've added a console.log(), but cannot find anything useful. I've seen others have this error raised here, but no answer was given on how to resolve it.
Any help will be much appreciated - whether retrying the request at this time or resolving the error so that it will continue (or restart) executing the response interceptor's code.

Vite cannot forward the request normally

I'm at vite config. TS configures the request broker, as follows:
// 开发服务器配置
server: {
host: true,
port: VITE_PORT,
open: VITE_OPEN,
proxy: {
"/MockServer": {
// target: "http://172.16.10.215:32340/",
target: "http://172.18.30.123:8510/gdm-analysis/",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/MockServer/, ""), //替换访问api的url适配服务端
},
},
strictPort: false, //接口被占用时尝试使用下个可用端口,
hmr: true,
},
I start the project locally and visit, and the request is correctly forwarded to http://172.18.30.123:8510/gdm-analysis/,but when I use my colleague's computer to access my local project, the request cannot be forwarded normally, header show:Provisional headers are shown

Not being able to remove cookies on nextjs in production

I am creating an application in NextJs and I set the cookie authorization when the user make login:
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", `Bearer ${jwtGenerated}`, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 60 * 60 * 12,
path: "/",
})
]);
This part of the code works perfectly, it sets the cookie in the browser. However when I log out, I make a request to the url /api/logout that executes this code:
import cookie from "cookie";
export default (req, res) => {
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", "false", {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 5,
path: "/",
})
]);
return res.status(200).json({ roles: null, auth: false });
};
however it seems that it does not work in production. When I'm at localhost it removes cookies and changes their value. However in production nothing is changed. The expiration remains the same, value and everything else.
Am I doing something wrong? Is there any other way to remove this cookie when the user make logout?
Are you using Vercel as the deployment platform? This bug is caused because Next.js's serverless features always return a 304 Not Modified. Quite frankly I don't know why this happens on the server, but I believe that it has something to do with HTTP requests on Next.js's internals.
In order to fix this problem, I made the logout request a POST request with a static key. This will prevent 304 Not Modified error from happening.
import cookie from "cookie";
export default (req, res) => {
if (req.method !== 'POST') return res.status(405).json({ status: 'fail', message: 'Method not allowed here!' });
if (req.body.key === 'static_key') {
res.setHeader("Set-Cookie", [
cookie.serialize("authorization", "false", {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: true,
maxAge: 5,
path: "/",
})
]);
return res.status(200).json({ roles: null, auth: false });
}
return res.status(400).json({ status: 'fail', message: 'Bad request happened!' });
};

ng serve --proxy-config proxyconfig.json not working

I'm building an app using MEAN stack. I'm using Proxy config file to make requests to the backend which is written in Node JS.
proxyconfig.json
{
"/api/*": {
"target": "https://localhost.com:3333",
"secure": false,
"changeOrigin": true,
"pathRewrite": {
"^/api": "https://localhost.com:3333/api"
}
}
}
Code in Component file
this.http.get("/api/posts",{responseType: 'text'})
.subscribe(
data =>
{
console.log('successs');
},
error =>
{
console.log(error);
}
);
Code in Node JS server
app.get('/api/posts', function(req, res) {
console.log('Posts Api Called');
res.status(200).send({ data: 'somedata' });
});
I'm getting 500 error when I inspect the request from Chrome. The GET method is not getting called at all. What could be the cause?
Finally, I made a silly mistake and this worked for me.
{
"/api": {
"target": "https://localhost:3333/api",
"secure": false,
"changeOrigin": true,
"pathRewrite": {"^/api" : ""}
}
}

Resources