How to get data from Nodejs to angular 6? - html

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

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

How to handle a JSON returned by Trello API in JS

So I'm working on a simple .html file .
I'm making the query:
var toDo= Trello.get('/lists/5d3ef8543a911e79f63df8c0/cards');
And I'm calling:
console.log(toDo);
And I'm getting this weird JSON
JSON returned by Trello API
So my problem is that I need to acces the responseJSON atributte, and I dont know ho to do it.
I already tried with toDo.responseJSON but it returns 'undefined'
How can I handle this type of JSON?
How can I access the atributes shown on the image?
Here is a basic example on how to handle the Promise:
Trello.get('/lists/5d3ef8543a911e79f63df8c0/cards')
.then(
(success) => {
console.log(success);
}
).catch(
(error) => {
console.log(error);
}
);

react native http request JSON Parse error

the error occurs sometimes but not all the time. (I keep pressing reload until it resume normal)
the error occurs on android emulator but never on iphone.
JSON Parse error: Expected '}' tryCallOne
C:\Users\xxx\node_modules\promise\setimmediate\core.js:37:14
C:\Users\xxx\node_modules\promise\setimmediate\core.js:123:25
_callTimer
C:\Users\xxx\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152:14
_callImmediatesPass
C:\Users\xxx\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:200:17
callImmediates
C:\Users\xxx\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:473:30
__callImmediates
C:\Users\xxx\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:337:6
C:\Users\xxx\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6
__guard
C:\Users\xxx\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:314:10
flushedQueue
C:\Users\xxx\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:17
it's just a very typical http request
fetchArticle(id) {
fetch("http://domain/api/articles/"+id)
.then(res => res.json())
.then(
(result) => {
console.log(result);
image_path = result.image_path;
data = result.data;
images = [];
data.slides.forEach(function (el, index) {
var image = image_path + "/" + el;
//console.log(image);
images.push({url:image});
});
this.setState({
isLoaded: true,
data: data,
image_path: image_path,
images: images,
});
//console.log(this.state.data);
//console.log(this.state.images);
},
(error) => {
console.error(error);
this.setState({
isLoaded: true,
});
}
)
}
I have totally no idea what's wrong with it. please help. thank you!
updated:
API response data
{"id":1,"title":"\u9999\u6e2f\u53cd\u4fee\u4f8b\u98a8\u6ce2\u6301\u7e8c\uff0c\u4e0d\u5c11\u6e2f\u5546\u7a4d\u6975\u90e8\u7f72\u64f4\u5f35\u6d77\u5916\u696d\u52d9\uff0c\u5206\u6563\u98a8\u96aa\u3002","heart":1,"address":"rewerfwr
fdsf sdfsdf
sdf","content":"擬申請「第二家園」\r\n《蘋果》早前亦到吉隆坡訪問當地電商情況,近年中國科網龍頭大舉進軍當地市場,如龍頭Shopee(創辦人為天津人李小冬)及Lazada(2016年被阿里巴巴收購)、淘寶亦十分流行,市場亦有Lelong.my等當地企業,競爭相當激烈。\r\n\r\n其中於巴生樓上店開設插花班、「Rose
Are
Red」聯合創辦人楊舒文表示,由於舖租僅1,000元令吉(約1,879港元),惟距離市區較遠,要靠網上吸引客人;她指對比不少當地盛行的電商,「客人見到產品的同時,</p>亦會見到其他同款產品,好容易淨比較價錢而冇考慮質素」。而掌舖可直接將商品上載到網上製成獨立網頁,所以深受不懂網頁製作的店主歡迎。\r\n</p>\r\n吳家嘉提到,大馬「第二家園」計劃近日成為香港熱門話題,他指如當地業務成熟,亦會考慮申請。</p></p>\n","fee":"\u7531\u500b\u5225\u9598\u53e3\u5c01\u9589"}
i have tried another non-chinese request with the same api call (different id) and it has no any json parse error on android emulator. Therefore I suspect it's related to UTF8 or charset problem.
It looks like the response isn't sending any object to be parsed.
Checking the res.status before doing res.json() would be helpfull to prevent that error.
I don't know if it is your own API, but if you are expecting an object only when the request succeeded, try setting the response status in the back-end (let's say, 201), and check in the front-end if the res.status is 201 before doing res.json().
Of course, if you are also expecting an object when the request failed in some specific cases, do the same for the errors and set a response status to be checked in front-end before doing the res.json()
Once it is done, you can console.log the res.status when the above conditions are not fulfilled, and maybe share the result so we can help you investigate what happened ?

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!

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