login.ts
onLogin() {
let input = new FormData();
input.append('email','ajith#gmail.com')
input.append('password','12356789')
this.http.post('http://worthyconsultants.in/training/api/v1/user/login',
input,{responseType: 'json'}).subscribe(res=>{
console.log(res)
},
err=>{
console.log(err)
})
}
This is my Login function but the response is an error.says parsing error
First you conform your post request send using POSTMAN tool if yes follow this link it help you or it may be backend side issue
[enter link description here][1]
https://www.youtube.com/watch?v=HgKx36cpu60
There was a print statement at the backend code,That's why it seems fine in the postman pretty view.
Related
I am new to working with API and I am working on a web-extension to fetch a random quote.
Each time I refresh the page the output works fine with response.data however, I would like to use each object from the responses... and not have the entire data on the page so I can add my custom styles.
I am using Axios + pure js
and I would like to access these values
Can someone please tell me, what I am doing wrong here?
For now, all I can access is request.data
axios
.get(url)
.then(function (response) {
showTextToUser(response.data);
//NOT WORKING console.log(response['verse']);
})
.catch(function (error) {
console.log(error);
});
Here's my request using axios
This is how axios response object look like
{
config:{},
data:{ --PAYLOAD YOU SENT FROM SERVER --},
headers:{},
request:{},
status: // status code,
statusText:''
}
I think you will find the verse object in data object as response.data.verse
I'm using http.get to get data from nodejs to angular. I want load some content on page loading. So, I'm just calling it in initialize method.
_initialize(): void {
this.http.get('http://127.0.0.1:3000/query/getId').subscribe(
data => {
console.log("success");
},
err => {
console.log("Error occured."+JSON.stringify(err));
}
);
}
In my server js,
app.get('/query/getId',function(req,res){
console.log("hi there");
})
I want to pass the data, but as of now the console message itself not displaying in node. And in browser I could see the message error occured. message":"Http failure during parsing for the url" . Can anybody tell me how to proceed with this?
You can specify that the data to be returned is not a JSON using the responseType. See the Requesting non JSON data
In your example, you should be able to use:
this.http.post('http://127.0.0.1:3000/query/getId',{}, {responseType: 'text'})
Add on node function:
res.json("hi there");
Try the following which uses JSON data:
app.get('/query/getId',function(req,res){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
I have the following api call in my service:
getData() {
return this.http.post<Object>(this.base_URL + "web_app/login/", JSON.stringify(this.login))
.subscribe(response=>{
console.log(response);
})
The response is an object with two attributes, access_token and Success. I get the following in my console:
{access_token: "...", Success: "Success"}
Success: "Success"
access_token:"..."
When I try to access the access_token attribute, using response.access_token, I get an error. Why is this and how do I fix it? Is the response I'm getting an object? Thank you!
Edit: this is what console gives
enter image description here
As your image shows you are getting the response on console, try accessing it as follows,
.subscribe(response=>{
console.log(response['access_token']);
})
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?
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.
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);
I'm not familiar with Angular, but looking at the docs:
See https://angular.io/api/http/Response
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 with 200 OK. And any subsequent API all with that JWT will also yield a 200 OK along with the response body which is usually JSON.
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.
res.status(200).json({
status: 'success',
results: tours.length,
data:{
tour:tours
}
});
Usually, Jsend is a good choice to response, and also by convention. Absolutely you can see the 'status' in response data and the actually data you want in the data.
according to the angular guide, we can add observe in the options of our request.
getforgetpassword(email: string): Observable<any> {
const url = this.gatewayUrl + `newPasswordFor/${email}`;
return this.http.get(url, {observe: "response"});
}
using observe type as response will give total response along with request status, which you can use in your logic of controller.
I would like to do something like the following with express.
let error = {errorCode:"1234"}
res.sendStatus(403, {error: error});
In my frontend javascript I'd like to catch the error and inspect it like so
getData(mydata).then((data)=> {
console.log(data);
).catch((error)=> {
console.log(error.errorCode);
});
for whatever reason this isn't sending back the json to my catch method and I'd like to know why and how I can send json when I send back a 403.
Use this syntax
res.status(403).send({errorCode:"1234"});
// or
res.status(403);
res.send({errorCode:"1234"});
Just in case , I just faced a similar case ... and found this post ... so to access the response body of a nodejs http 4xx-5xx on the client side, you can use the response.data property of the error object ...
for example in the catch block :
(err => console.log(JSON.stringify(err.response.data))
to access an object or data send in a response with a >= 400 http status
like from a nodejs server for example with
return res.status(403).send({data});
At least it worked for me, Hope this will help