I’m making a call with ajax to my db to get some data. And I try to limit it to a specific Id. And I got the backend working. it works when I visit the specific localhost url or when I call it from Postman. I then get the expected value. However when I try to make a call from my client with AJAX I just don’t get anything at all. I got into a thing where sometimes it would work and sometimes it didn’t.
const GetUserById = (id) => {
let url = "/Users/1";
$.get(url, (gotUser) => {
alert(gotUser.id);
})
}
I have this method that I just hardcoded to go to /Users/1 for testing purposes. And when I call this in postman or go to localhost:8080/Users/1 I get the thing I expect. However here It just doesn’t go anywhere at all.
app.get("/Users/:id", (request, response) => {
let sqlCode = "select Id, Username, [Password], Credits from Users Where Id = " + request.params.id;
sql.query(connString, sqlCode, (error, result) => {
if (error) {
console.log(error);
}
else {
response.json(result);
}
});
});
The server side if that’s interesting.
EDIT: added a try catch like this. it doesn’t even get to the catch. It get’s to the line that’s $.get(url, (gotUser) => { then it goes to the end of the function and doesn’t get anything.
try {
$.get(url, (gotUser) => {
alert(gotUser.id);
})
} catch (error) {
console.log(error);
}
2
Answers
A typical issue with processing ajax requests are CORS. In your case a quick fix to that would be to specify at the response headers to allow the origins, like that:
In a more general way you might need to specify it in application level, or use any package to deal with that(cors).
EDIT —
If it is a cors issue try something along these lines