Angular2 Http.Post - How to view webapi response - json

I'm new to Angular2/Typescript and I'm writing my first web application.
I'm trying to call a webapi using POST, it works, if I intercept the call using FIDDLER I can see the Json response.
Now, how I can log in the browser console the json ouput?
The code is this:
code call
var s = this.myService.doSearch();
s.subscribe(
data=> this.data = data,
error => this.errorMessage = <any>error
);
console.log(s);
service method
doSearch() {
var url = this.baseUrl;
return this.http.get(url)
.map(response => response.json())
.catch(this.handleError);
}
My question is: how and where I can view and manage the Json Output ?
Thanks

You need to console.log it after the async code is finished:
var s = this.myService.doSearch();
s.subscribe(
data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);

If you are debug or run your application in browser you can got to inspect and then move to the Network tab. In this tab select your POST Request and the go to the tab Response and voila there is your json Response
Edit:
To log all response data do this:
return this.http.get(url)
.map(res => res.json())
.subscribe(data => { console.log(data);})
.catch(this.handleError);
}

Try this this will print what you have in your returned observable .
var s = this.myService.doSearch();
s.subscribe(data=> {
this.data = data;
console.log(data);
},
error => this.errorMessage = <any>error
);
Always remember If you want to get data from observable.you need to subscribe it.
you can't log it like this console.log(s); because s returns an observable. you should subscribe and refer those data inside the subscribe .

Related

Is there a way to get a nested JSON object using react native?

My JSON file can be found using this link. The object "features" have a nested object called "properties", where I want to access the data from that object. I've tried to use the useEffect() hook from React and implemented that in the code below. I tried to get the "properties" sub object by implementing the following code: data.features.properties, but that returns undefined. What code am I implemented wrong or what logic is incorrect?
useEffect(() => {
fetch('https://www.vaccinespotter.org/api/v0/states/' + stateAbb + '.json')
.then((response) => response.json())
.then((json) => {
setData(json);
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, [stateAbb]);
stateAbb is the state abbreviation for the state that the user selects in a text input on a different screen. propData seems to store the "features" object as I have used the alert() function and typeof() to determine that propData is an object.
I've tried to JSON.parse() and implemented some other StackOverflow answers, such as this and this. The effect still remains the same. data.features works as an object but data.features.properties returns undefined.
Any help would be appreciated!
Thanks!
React hooks doesn't allow async await in useEffect so you can create new function like this
useEffect(()=>{
fetchData()
},[])
const fetchData = async ()=>{
try{
const response = await fetch('https://www.vaccinespotter.org/api/v0/states/' + stateAbb + '.json')
const json = await response.json()
console.log(json); // your data is here!
}catch(err){
console.log(err)
}
}

Javascript - Return json from fetch in an Object

I'm trying to make an application to get the recipes from https://edamam.com and I'm using fetch and Request object.
I need to make 3 request, and i thought that most beautiful way for do it is make an Object and a method that return the data in JSON.
I declarated into constructor a variable called this.dataJson, and i want to save there the data in JSON from the response. For that purpose i use this.
The problem is that i have a undefined variable.
.then( data => {this.dataJson=data;
console.log(data)} )
This is all my code.
class Recipe{
constructor(url){
this.url=url;
this.dataJson;
this.response;
}
getJson(){
var obj;
fetch(new Request(this.url,{method: 'GET'}))
.then( response => response.json())
.then( data => {this.dataJson=data;
console.log(data)} )
.catch( e => console.error( 'Something went wrong' ) );
}
getData(){
console.log("NO UNDFEIND"+this.dataJson);
}
}
const pa= new Recipe('https://api.edamam.com/search?...');
pa.getJson();
pa.getData();
I'm new studying OOP in JS and more new in Fetch requests...
If you guys can help me... Thanks very much!
Here's a solution using async-await (and a placeholder API):
class Recipe {
constructor(url) {
this.url = url;
this.dataJson;
this.response;
}
// the async keyword ensures that this function returns
// a Promise object -> we can use .then() later (1)
async getJson() {
try {
const response = await fetch(new Request(this.url, {
method: 'GET'
}))
const json = await response.json()
this.dataJson = json
} catch (e) {
console.error('Something went wrong', e)
}
}
getData() {
console.log("NO UNDFEIND:", this.dataJson);
}
}
const pa = new Recipe('https://jsonplaceholder.typicode.com/todos/1');
// 1 - here we can use the "then", as pa.getJson() returns
// a Promise object
pa.getJson()
.then(() => {
pa.getData()
});
If we want to stay closer to your code, then:
class Recipe {
constructor(url) {
this.url = url;
this.dataJson;
this.response;
}
getJson() {
// var obj; // not needed
// the "fetch" always returns a Promise object
return fetch(new Request(this.url, { // return the fetch!
method: 'GET'
}))
.then(response => response.json())
.then(data => {
this.dataJson = data;
// console.log(data) // not needed
})
.catch(e => console.error('Something went wrong'));
}
getData() {
console.log("NO UNDFEIND:", this.dataJson); // different syntax here
}
}
const pa = new Recipe('https://jsonplaceholder.typicode.com/todos/1');
// using "then", because the "fetch" returned a Promise object
pa.getJson()
.then(() => {
pa.getData();
});
The problem with your original code is that you initiate the request (pa.getJson()) and then immediately (on the next line) you want to read the data (pa.getData()). pa.getData() is called synchronously (so it happens in milliseconds), but the request is asynchronous - the data needs time to arrive (probably hundreds of milliseconds) - so, it's not there when you try to read it (it simply hasn't arrived yet).
To avoid this you have to use a technique to handle this asynchronous nature of the request:
use a callback function (blee - so last decade)
use a Promise object with then() (much better) or async-await (yeee!)
and call the pa.getData() when the response has arrived (inside the callback function, in the then() or after awaiting the result).

"Http failure during parsing for http://localhost:8080/"

extractData = (res: Response | any) => {
return res.body || {};
}
getData() {
return this.http.get('http://localhost:8080/test',
observe: 'response'
).pipe(
map(this.extractData));
}
The call is successful, I'm able to see the response in network tab but when I tried to log the response in console, I'm getting parse errors. Can anyone please help me
The getData() function doesn't have any return type mentioned.

React failing to parse a JSON object from server

I'm running into this error:
Uncaught (in promise) SyntaxError: Unexpected token [ in JSON at position 1
when I pass a JSON object containing an array of JSON objects to my component. The object structure is:
{ "arrayName": [{object},{object},{object}, etc...] }
I've run the JSON through a validator and it comes up clean but my api call always returns the same error.
export const api = 'http://localhost:8000'
export const headers = {
'Content-Type': 'application/json',
'Accept' : 'application/json',
}
export const getAll = () =>
fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
This is where it gets called in App.js:
componentDidMount() {
eventsAPI.getAll().then((events) => {
console.log(events)
this.setState({ events })
})
}
I'm not sure why I'm getting the error, I know I'm sending a valid JSON object, is the way I'm receiving it wrong? I can see in the network tab of the dev tools that the correct format is being passed and received. I just don't know where exactly I've gone wrong. This is the response logged from the server. I can see the XHR response in dev-tools but it's a bit big to post here 25+ objects.
You need to modify getAll to actually return something. As it is a fetch, you can just return that, which will return the promise.
export const getAll = () =>
return fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
Now wherever you use getAll be sure to call then:
getAll().then(data => console.log(data))

How to log Mocha/Chai HTTP requests

Hi I am new to Mocha/Chai.
I am trying to test some HTTP requests. If would be nice if I could log the actual test request to debug it.
The code I am using looks something like
describe('Get token for super user', () => {
it('it should get a valid token set', (done) => {
let req = chai.request(app)
req
.get('/oauth/token')
.set('Content-Type','application/x-www-form-urlencoded')
.set('Authorization','Basic blah')
.field('grant_type', 'password')
.field('username', superUser)
.field('password', superPass)
.end((err, res) => {
console.log('*******' , req)
res.should.have.status(200)
done()
})
})
})
How would I log the request itself, I don't see a neat way of doing this from the API docs ?
Simplest way to get and log all info about request - response object:
chai.request('http://...')
.post('/endpoint')
.send('{"a":1}')
.end((err, response) => {
console.log(response);
done();
});