Response.Json() is not a function - json

I'm following an rxjs that shows how to use rxjs with http calls in angular. But when i'm,trying to use response.json in the mapping function, i've an error in the console saying that: ERROR TypeError: response.json is not a function. this is the code of my service:
mappingFn() {
return this.http
.get('https://opentdb.com/api.php?amount=10')
.pipe(map((response: Response) => response.json()))};
this is the code of the components:
this.svc.mappingFn().subscribe({
next: (res) => {
console.log('mapping:', res);
},
});
I looked on different blogs, but i couldn't find something usefull. Please help me. Thank you

This can be influenced by your response. Some of them does not work directly. Go to the network tab and watch your data model. On the other side, make sure that you actually have a response, and response isn't undefined.

You don't have map the result to json, that was happen automatically by HttpClient.get(). Remove the map and write mappingFn as.
mappingFn() {
return this.http
.get('https://opentdb.com/api.php?amount=10')};

Related

Exception Handling w/ Axios

I have an API written in .Net that's being called from a (server-side) JavaScript app. The behavior is very odd and I can't explain.
If I hit the endpoint from Postman - with the same parameters - it works as expected (a MSSQL database is updated), and no errors.
However, when the code below is executed, even though the database is updated, the catch is triggered but - here's the weird part - the err object is {}, just an empty object.
Also, because the err object is empty (not undefined or null), the res.status(...) call triggers another error, obviously because there are no properties on the object.
Any ideas? Thanks in advance.
axios.post('task', formData, { headers: formData.getHeaders() })
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log('#ERROR#')
res.status(err.response.status).send(err.response.data.Message)
})
})
Did you try this?
res.send(result.data)
I hope it will work.

Why is my API requset returning only a string payload [JavaScript]

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

How to get data from Nodejs to angular 6?

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 }));
});

Angular Response.json() not documented

I see Response.json() method being used a lot, and I'm using it myself, but either I'm missing something or the documentation for the Response class is incorrect.
Example:
getCurrentTime() {
return this._http.get('http://date.jsontest.com/')
.map((res:Response) => res.json())
}
On the Angular site at https://angular.io/docs/ts/latest/api/http/index/Response-class.html, I don't see the method as a member of the Response class.
If .json is not a member of the Response class, can someone point me in the direction of understanding how this works.
Or if the documentation is wrong, someone please say so.
Thanks in advance.
If you look at the API Reference for Response, you'll see that Response extends Body. If you try to search for Body, you won't find it, which probably means it isn't public. If you look at the source code for Body, you'll see the code for json
/**
* Attempts to return body as parsed `JSON` object, or raises an exception.
*/
json(): any {
if (typeof this._body === 'string') {
return JSON.parse(<string>this._body);
}
if (this._body instanceof ArrayBuffer) {
return JSON.parse(this.text());
}
return this._body;
}
Let me know if you need explanation of the source. It looks pretty self-explanitory to me though.
Actually, the HTTP Client documentation (Process the response object)
says:
Parse to JSON
This is not Angular's own design. The Angular HTTP client follows the Fetch specification for the response object returned by the Fetch function. That spec defines a json() method that parses the response body into a JavaScript object.
So Angular2 implements the Fetch Specification, which includes the specification for the mentioned Body mixin, Angular2's Response class is extending, including the .json() method.
The json() method, when invoked, must return the result of running consume body with JSON.
As you can see in peeskillet's link, Angular2 is implementing all specified methods of the Body mixin, except of formData().
I had the same problem and this is how the error go away:
In the new version of Angular 4+, you need to imports rxjs from:
import { map } from 'rxjs/operators';
instead of from importing from:
import 'rxjs/add/operator/map';
Next, change the .get() to .get() and also you have to use pipe for angular 4+ as below:
getCurrentTime() {
return this._http.get<any>('http://date.jsontest.com/')
.pipe(map((res:Response) => res.json()));
}
Hope that Helps...!

Ionic2 http request. XML to json?

Hi I am trying to make a http request from this rss feed. I tried this:
makeRequest() {
this.http.get('http://www.gazetaexpress.com/rss/auto-tech/?xml=1')
.subscribe(data => {
this.posts = data;
console.log("request funktioniert");
}, error => {
console.log(JSON.stringify(error.json()));
});
}
When I use {{posts}} in the html page it returns:
Response with status: 200 OK for URL: http://m.gazetaexpress.com/mobile/rss/auto-tech/?xml=1
When using {{post | json}} it return the whole html page. I tried using:
this.http.get('http://www.gazetaexpress.com/rss/ballina/?xml=1').map(res => res.json())
instead for the first line but it returned an error:
TypeError: error.json is not a function
Please help me :D
EDIT
I imported the xml2js library and typings and imported in the ts file:
import * as xml2js from "xml2js"
And changed the request to:
makeRequest() {
this.http.get('http://www.gazetaexpress.com/rss/auto-tech/?xml=1').subscribe(data => {
this.posts = data;
xml2js.parseString(this.posts, function (err, result) {
console.log(result);
});
}, error => {
console.log(JSON.stringify(error.json()));
});
}
The console returns undefined...
EDIT 2
Okay I hotfixed the issue. I just took the hole string and cut it down to pieces using the node structure and using this.posts.replace(/\\t|\\n|\\r/gi, ""); to get rid of escaped chars. Surely there must be a good library working on this issue my code is pretty badass ;). I will overlook this code later on for now it`s working and thats okay. If you have some better ideas feel free to tell me :D
If you get a response of Status 200 OK you should be able to show the results as they are ordered on the website you are making the http request.
Try to fetch the data each when subscribing and use an asnyc pipe in your html code this should do the trick