Currently, I am developing a custom HTTP client using JavaScript. Although my code appears to be correct, I keep receiving 404 errors for my requests. This code is being executed on a NodeJS (ExpressJS) server that includes a handler as shown below:
app.post('/api/update', (req, res) => {
res.send(req.body);
});
Below is the JavaScript code I am using:
const customHTTPClient = (method, url, post) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onload = () => {
const statusText = xhr.statusText || '';
const response = ('response' in xhr) ? xhr.response : xhr.responseText;
let status = xhr.status === 1223 ? 204 : xhr.status;
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
}
try {
return resolve(JSON.parse(response));
} catch (error) {
return resolve(response);
}
};
xhr.onerror = () => reject('Error');
xhr.ontimeout = () => reject('Timeout');
xhr.onabort = () => reject('Abort');
xhr.send(JSON.stringify(post) || null);
});
};
customHTTPClient('post', '/api/update', defaultData).then(response => {
css.value = response.data;
console.log(response);
}, error => {
console.error(error);
});
IMPORTANT: defaultData
is an Object