Express res.status(200).json(...) only sending json message. How to retrieve status code?
Solution 1
A little bit late, but another option is to include the status in the JSON object:
res.status(201).json({message: "Successfully Registered", status: 201})
Now you can check the status in the front end doing res.status
and use this to proceed with another action.
Solution 2
I'm not familiar with Angular, but looking at the docs:
You'll need to do something like:
http
.request('example.com')
.subscribe(response => console.log(response.status));
- Sure, checking for
200
is fine. Typically with a REST API (inferred from what you've shown), after a login you're given back a JWT along with200 OK
. And any subsequent API all with that JWT will also yield a200 OK
along with the response body which is usually JSON.
Solution 3
1- You can do res.status(200).send("You message here");
2- I would say your best option when doing the login and authenticating credentials is to create a session as such
req.session.user = req.body.username //username is the name attribute of the textfield
and then redirect to any page you'd like/you can also set status to 200
res.status(200);
Solution 4
You should tell your angular http client that you want to get the response status. By default, angular deserialize the response body, but you can set request option.observe:'response' to do so.
postData(model: MyModel): Observable<HttpResponse<{status: string}>> {
return this.http.post<{status: string}>(
model, { observe: 'response' });
}
See https://angular.io/guide/http#reading-the-full-response for details.
PS: sending a { status: 'message' } is not very useful, you may return an { id } or even nothing.
Related videos on Youtube
![Vincent Nguyen](https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=256)
Vincent Nguyen
Updated on June 04, 2022Comments
-
Vincent Nguyen about 2 years
After a successful creation of new item in my database I send:
res.status(201).json({message:"Successfully Registered"});
On my angular front end I am able to
console.log(res)
and receive:{message: "Successfully Registered"}
1) How do I get the status code on the front end?
res.status
returns undefined. The only response I'm getting is the JSON.2) What would be the best way to confirm successful desired api calls? For example, when I log in and credentials are correct, should I check for a
200
and then proceed? Or send a custom JSON message and check if the message for example says "Successful login" then proceed?