I have a project using express, axios and fs.writeFileSync cause ERR_CONNECTION_REFUSED err.
For demo purpose, I made this repo, the architecture / idea is the same, but I am not able to replicate the same err, but it is only for you to understand what I try to achieve. Following error message are from the real project, but I modify it to align with the demo repo.
in chrome console
getDetail error Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 GET http://localhost:3001/detail net::ERR_CONNECTION_REFUSED
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:76
wrap @ bind.js:9
(anonymous) @ detailApi.js:13
step @ tslib.es6.js:100
(anonymous) @ tslib.es6.js:81
(anonymous) @ tslib.es6.js:74
__awaiter @ tslib.es6.js:70
getDetail @ detailApi.js:4
runCallEffect @ redux-saga-core.esm.js:524
runEffect @ redux-saga-core.esm.js:1204
digestEffect @ redux-saga-core.esm.js:1271
next @ redux-saga-core.esm.js:1161
currCb @ redux-saga-core.esm.js:1251
runSelectEffect @ redux-saga-core.esm.js:731
runEffect @ redux-saga-core.esm.js:1204
digestEffect @ redux-saga-core.esm.js:1271
next @ redux-saga-core.esm.js:1161
currCb @ redux-saga-core.esm.js:1251
(anonymous) @ redux-saga-core.esm.js:481
exec @ redux-saga-core.esm.js:31
flush @ redux-saga-core.esm.js:87
asap @ redux-saga-core.esm.js:46
chan.put @ redux-saga-core.esm.js:375
(anonymous) @ redux-saga-core.esm.js:1412
dispatch @ VM99:1
in network tab
Headers
====
Request URL: http://localhost:3001/detail
Referrer Policy: strict-origin-when-cross-origin
Accept: */*
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Origin: http://localhost:3000
Sec-Fetch-Mode: cors
Some findings and code below
If I remove fs.writeFileSync or change it to a delay loop, no network err. Everything is good.
Use either fs.writeSync or fs.writeFileSync network cause network err
const cors = require("cors");
const express = require("express");
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");
function server() {
const server = express();
server.use(cors());
server.use(bodyParser.json());
server.get("/detail", (req, res) => {
const data = require("./detail.json");
res.status(200).jsonp(data);
});
server.post("/agree", (req, res) => {
try {
const agree = req.body.agree;
const filePath = path.resolve(__dirname, "./agree.json");
let data = JSON.parse(fs.readFileSync(filePath));
data.agree = agree;
// * If I remove it or change it to a delay loop, no net work err
// * fs.writeSync or fs.writeFileSync network cause err
fs.writeFileSync(filePath, JSON.stringify(data));
res.status(200).jsonp({ success: true });
} catch (error) {
throw new Error("error", error);
}
});
return server;
}
module.exports = server;