Ionic2 http request. XML to json? - 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

Related

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

Json data only loads correct once you refresh the page?

I have two issues but I believe the second issue will be fixed once the first is fixed (question title).
I am receiving JSON from woocommerce. I can call for this data by using fetch of course on client side and it looks as such in the code:
async componentDidMount() {
const response = await fetch('/products');
const json = await response.json();
this.setState({
data: json,
})
// other code ....
}
When I go on the browser I get this error regarding my json data:
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
With the following error in the console.log:
index.js:6 GET http://localhost:3000/products 500 (Internal Server Error)
index.js:6 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Once the webpage is refreshed...this all disappears, everything becomes A-OKAY, why? and how do I go about rectifying this?
My JSON data when consoled and the page refreshed returns an object - no '<' is there. Also I don't know why I get the 500 error shown above? I am learning node.js - so I think this is a server side issue as I had no issues before I split my code to client and server.
help?
What is happening is the data call you do takes time to load the data.
Till then the this.state.data is null. The error
Unexpected token < in JSON at position 0
is because you are trying to process the this.state.data but finds null. You need to make sure you handle what needs to be displayed when data is null.
Also, I think you don't need the await before response.json()
The 500 server error is a server side issue.
To stop this whole refreshing the page issue; I had to fix my server file (node.js of course)
My get request had originally looked like this:
let response;
app.get('/products', (req, res, err) => {
WooCommerce.get('products', function(err, data, res) {
response = res;
});
res.status(200).json(JSON.parse(response));
});
The issue here was that I was calling /products with fetch which url didn't point to anything but another API call, which only got called once I forced it pass the first url call I guess using a page refresh. Forgive my understanding here.
The correct code was calling Woocommerce api first then passing its response to the /product url so I can fetch it in the front end, like so;
let response;
WooCommerce.get('products', function(err, data, res) {
response = res;
app.get('/products', (req, res, err) => {
if (res.status(200)) {
res.status(200).json(JSON.parse(response));
} else {
console.log('theres an error', err);
}
})
});
And Tarrrrdaaa no refresh issue/SyntaxError error!!!
As one of the answers says, this error happens when you try to parse a nullish value. You can fix this issue by making sure the data is defined before trying to parse it:
if(data){
JSON.parse(data);
}

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

How to generate specific json with jqwidgets and angular?

I'm trying to export the data of my datatable into a json file.
The table is create with JQwidget on Angular6 and the data come from an API.
But, with the jqwidgets method exportData('json');, only can make a format of a json of the table.
[{"id":"1","name":"test"},
{"id":"2","name":"toto"}]
jsonExport(): void {
this.myDataTable.exportData('json');
};
I don't know how to change the format of the json to have something like that:
["number":"2",
"1":{"id":"1","name":"test"},
"2":{"id":"2","name":"toto"}]
Thanks
I manage to do what I wanted, it goes like that:
First, You can't do it with JqWidgets https://www.jqwidgets.com/community/topic/how-to-generate-specific-json-with-exportdatajson-jqwidgets-and-angular/
Then, my solution is:
I created the String inside my Nodejs API as a GET.
app.get('jsonfile', function (req, res) {
res.header("Content-Disposition", "attachment;filename=\filename.txt\"");
connection.query('select * from heroes', function(error, results, fields) {
if (error) throw error;
var JSONstring = "[";
...
...
...
JSONstring = "]";
res.end(JSONstring);
console.log(JSONstring);
});
});
res.header('Content-Disposition', 'attachment;filename=\filename.txt\""); is mandatory for my solutio if you want to make this JSON string downloalable as a file.
I tried to use this end-point just like the others but I had this problem :
ERROR
Object { headers: {…}, status: 200, statusText: "OK", url: "http://localhost:3000/jsonfile", ok: false, name: "HttpErrorResponse", message: "Http failure during parsing for http://localhost:3000/jsonfile", error: {…} }
Because it was not working with a button click and ts function.
Instead I just made this:
<a href="http://localhost:3000/jsonfile" ><button>Creation JSON File</button></a>
It works for me, but if there are better solutions, I will be glad to know.
Thanks all for your help!

Angular 2 to-do app not storing new tasks in MySQL database

I'm doing this tutorial using Ionic 2 and Angular 2 to create a to-do app. I swear I am typing in the exact code he gives us in the video, but my app isn't storing items to the database. (The MySQL database is running just fine.) When it tries, I get this error:
Response_body: "failed"
headers: Headers
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://localhost/note/store.php"
__proto__: Body
it fails! home.ts:25
and "[object Object]" in console.log. So the request is getting somewhere, but it's not getting saved for some reason and I can't tell why.
The teacher (tutor? Tutorialer?) looked at my detail.ts and said he couldn't see a post function going to store.php. My understanding is that this function in home.ts does that:
addDB(obj){
this.http.post("http://192.168.1.162/note/store.php",obj).
subscribe(data =>{
console.log(data);
var resp = data.text().trim();
if(resp == "success"){
console.log("it works!");
this.loadDB();
}else{
console.log("it fails!");
}
}, err=>{
console.log(err);
})
}
but when I said so, he didn't seem clear on what he needed anymore. I thought maybe StackOverflow would know what to do.
There are multiple .ts and .html and .php files, so I couldn't make a fiddle; I've put them all up on GitHub instead. Specifically, home.html and home.ts, app.module.ts, detail.html and detail.ts, and these php files are really the only ones I have touched.
I feel like this has to be something simple and ridiculous like "this function is in the wrong file and you didn't notice he switched which one he was using right here" but I swear I've looked over it repeatedly....
When using http in angular 2, you would have to parse the response using a .map() function like so :
this.http.post("http://192.168.1.162/note/store.php",obj)
.map(res => res.json())
.subscribe(data=>{
},
err=>{
})
EDIT : Using Promises instead of observable :
import 'rxjs/add/operator/toPromise';
this.http.post("http://192.168.1.162/note/store.php",obj)
.toPromise()
.then(data=>{
})
.catch(err=>{
})