I am working on a JavaScript and Node.js project, and my POST requests keep rising "TypeError: Failed to fetch"; however, my GET requests work well. And my POST requests cannot even been finished. I checked the ‘Network’ tab, and the timing tab within it shows the request is stalled and not finished.
I also added CORS headers in server.js, which is not working. And I saw other post about it said adding ‘event.preventDefault()’, and this doesn’t work for me either as I added it at first.
Below are the codes of fetching:
async function handleFormSubmit(postData) {
// Send a POST request to your API endpoint
await fetch("http://localhost:3000/api/submit", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((response) => response.json())
.then((data) => {
console.log("POST Response:", data);
})
.catch((error) => {
console.error("POST Error:", error);
});
}
postForm.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(postForm);
const postData = {
model_id: formData.get("model_id"),
prompt: formData.get("prompt"),
bad_response: formData.get("bad_response"),
};
handleFormSubmit(postData);
});
—-server.js—-
const modelRoutes = require('./src/routes/modelRoutes');
app.use(cors());
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000'); // Replace '*' with your allowed origin
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
next();
});
app.use(bodyParser.json({ limit: '10mb', extended: true }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
app.use(express.static(path.join(__dirname, './public')));
app.use(express.json());
app.use('/api', modelRoutes);
—-modelRoutes.js—-
router.post('/submit', hallucinationController.submitHallucination);
—-controller—-
const submitHallucination = async (req, res) => {
try {
const { model_id, prompt, bad_response } = req.body;
// Use the public key to verify the request (optional).
console.log('controller:', prompt); //Here cannot reach for now
const mId = mongoose.Types.ObjectId(model_id);
const newSave = {
model_id: mId,
prompt: prompt,
bad_response: bad_response,
p_tuned: false,
};
// Save the hallucination data to your database (e.g., HALLUCINATION table).
const hallucination = new Hallucination(newSave);
const saved = await hallucination.save();
// Return a success message.
Utilities.apiResponse(
res,
200,
'Hallucination submitted successfully!',
{},
);
} catch (error) {
console.log('error:', error);
Utilities.apiResponse(res, 500, error);
}
};
Does anyone know what is the problem?
2
Answers
Ensure that your fetch options include the correct method ("POST") and headers. In your handleFormSubmit function, you are setting headers and the body but not including the actual data:
Try This Code For Your handleFormSubmit Function —>
In your
postForm.addEventListener
you have this line:This means you are passing the
postData
object to thehandleFormSubmit
function. I am going to assume you have checked to make sure all of your data is contained inpostData
with aconsole.log(postData)
just before you callhandleFormSubmit(postData);
.Now for some reason you never send the
postData
object because in the body of yourpost
request you are sending an empty object:You need to send the
postData
in the body like so:Your routing looks fine. The
http://localhost:3000/api/submit
will be caught byapp.use('/api', modelRoutes);
which will then route to therouter.post('/submit',)
to invoke yourhallucinationController.submitHallucination
function.