When I send a GET req from my client to my Express server it sends the data to the client but I get an XMLHttpRequest ready state of 1 and a status of 0 and it never logs the response text.
Client:
req.onreadystatechange = function() {
console.log(this.readyState);
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
req.open('GET', url + 'users', true);
req.send();
Server:
app.get('/users', function(req, res) {
res.send(users);
});
If anyone can tell me why I can't receive the array of users on client side and how to fix it. That would be great.
First I would use fetch
javascript because it looks more natural.
/* on server */
app.get('/users', function(req, res) {
res.send(users);
});
/* on client */
fetch('/users').then(async (response) => {
if (response.status === 200) {
console.log(await response.text());
// do you receive something ?
}
else {
throw new Error('something unexpected occurred');
}
}.catch(err => { console.err(err) })
If you don't receive anything, then you should check if your front page is served from the same data-providing server because when you call for /users
the browser is prepending the host to the path. So if both your client page and your back server is not running on the same host it will fail.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.