I am a newbie in NodeJs and i have to shift my code igniter server api's to node js .
I am using requestify to fetch all the data from a webservice and once this is achieved i will
call insert method to save all the entries.
Following is my code which i am using :-
requestify.get('SERVER_URL_CODE_IGNITER_API')
.then(function(response) {
// This one works but gives me all the json element with a backward slash like
// containing escaping character . Which i dont want
res.jsonp(response.body);
// When using following line i get an error
// Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND',
// syscall: 'getaddrinfo
// response.getBody();
}
);
My understanding is that response.getBody() should work and give the desired result without
escape characters but i am not able to get that working while response.body works but gives
me all the server data with backward slashes like this :-
"[{\"id\":\"212\",\"uid\":\"304\",\"fromLat\":\"28.5962491\",\"fromLon\":\"77.3396212\",\"toLat\":\"28.4594965\",\"toLon\":\"77.0266383\",\"fromName\":\"Sector 12, Noida, Uttar Pradesh, India\",\"toName\":\"Gurgaon, Haryana, India\",\"startTime\":\"08:00 Hrs\",\"returnTime\":\"06:40 Hrs\",\"carModel\":\"suzuki baleno\",\"fuelType\":\"CNG\",\"chargePrice\":\"\",\"smoking\":\"Doesnt Matter\",\"name\":\"Ankur Gupta\",\"image\":\"http:\/\/graph.facebook.com\/100000725036031\/picture?type=large\",\"email\":\"ankur1040#gmail.com\",\"fbid\":\"100000725036031\",\"age\":\"0\",\"sex\":\"0\",\"regid\":\"abc\",\"points\":\"0\",\"contact\":\"9711778805\"}]"
When you are using response.getBody(); you are not sending response to the client. I guess you are trying to send the response to the client. You will need to do
res.jsonp(response.getBody());
response.body only gives you raw response body. you can do
console.log(response.body);
and
console.log(response.getBody());
to compare your output.
I am guessing you are using express framework?
your request handler should look like this
function(req, res){
//other codes
requestify.get('SERVER_URL_CODE_IGNITER_API')
.then(function(response) {
res.jsonp(response.getBody());
});
}
Related
Some days ago I have started working on an Angular project, and how my "infrastructure" works is: Angular (front-end) connects to the node.js server (back-end) which if needed sends a request or query to an api server or a mongo database.
Now.. the response of node.js back to Angular is formatted as json so an example could be (response = { "date": getDate() } ). The problem comes with how can I access that response or more specifically.. access the date child? This is how I did it:
let url = "http://localhost:3000/checkdate"
this.http.post(url, data).subscribe((responsedata) => {
console.log(responsedata.date);
})
The the 3th line is where the error stays at, and it says "Property 'date' does not exist on type 'Object'.", anyone who can help me with it?
Also if you need, this is what I did with node.js to send a response back formatted as json:
app.post("/checkdate", (req, res) => {
console.log("New post request recieved!");
res.json({
"date": "12.31.2000"
})
})
I really don't seem to find a way or answer on the internet to solve this issue.
Thanks for your help and time!
Can you try responseData.obj.date?
function createData(req, res) {
console.log('trying to store Data.')
console.log('testing log ' + req.body.productID)
app.create_data(req, function (err, response) {
console.log('while returning' + response)
console.log('while returning error is '+err)
if(!err){
var jsonString = {}
jsonString['Result'] = "Success"
res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(jsonString))
res.end()
}
else{
var jsonString = {}
jsonString['Error'] = err.description
res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(jsonString))
res.end()
}
})
}
I've seen the following code for creating data in a REST API example. I can't understand a few things about it, can anyone please explain the overall purpose of this snippet?
What is jsonString['Result'] = "Success" doing, since we have initialized with an empty string?
These is a GET API, where is my code getting data from the text fields?
What does app mean in this Node.js snippet?
Why are we giving the same name that we already gave, like so: app.app.create_data?
This code snippet will create a JSON response to some API route.
This line assigns the string value "Success" to the jsonString object under the 'Result' key. It's a way to store key-value pairs in a JavaScript Object.
This snippet doesn't send anything more, than just what the jsonString object holds, which is either "Result" with the "Success" message or "Error" with a description. It will be converted to JSON and will be sent as a response:res.send(JSON.stringify(jsonString)).
Generally 'app' is an instance of some HTTP server in Node.js
It's just a structuring/naming practice, this can be highly different from project-to-project.
To get started with Node.js apps, check out these links:
Learn Node.js in 1 hour YouTube video
Gettings started with Node.js apps blog series
Creating a simple REST API tutorial blog entry with Express.js
I'm trying to post some data to a Python backend that i made with Flask. I'm using SuperAgent in a React component. For some reason i keep getting HTTP error 400.
I've read many posts about similar problems using JQuery and flask. The solution there is to set the contentType the same way i have and also JSON.stringify the data. I've tried stringify but it doesn't change anything. Still getting an HTTP 400.
Any ideas?
JS code:
request.post(link)
.set('Content-Type', 'application/json; charset=utf-8')
.send({tag: 'tag1', comment: 'Cool'})
.end(function(err, res){
console.log(res);
});
Python function/endpoint:
#app.route('/api/leavecomments', methods=['POST'])
def comment_to_photos():
comment = request.form['comment']
print(comment)
tag = request.form['tag']
...
So the issue for anybody else that has this problem, they need to use method named get_json which will have the values being passed to it in JSON format. In the case of the code above it was looking for those values as a query string post parameters, which is typically sent via form posts. In the case of an AJAX JSON post, the data exists inside the request.body.
For more information check out...
http://flask.pocoo.org/docs/0.10/api/#flask.Request.get_json
I'm trying to use Parse Cloud Code to run a python script. I'm passing a parameter, but I seem to be getting an error. I'm not 100% sure what the problem is, but it seems like I'm not composing the url correctly. Any help would be appreciated.
My python code looks like this:
# a function that makes a sentence more exciting
def excited(sentence):
return sentence + '!!!'
Here's my code in main.js:
Parse.Cloud.define('testFunction', function(request, response) {
var someParam = request.params['testString'];
var url = 'http://mywebsite.com/test.py/excited&sentence=' + someParam;
Parse.Cloud.httpRequest({
url: url,
success: function(httpResponse) {
console.log(httpResponse.headers);
console.log(httpResponse.text);
response.success();
}, error: function(httpResponse, error) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
});
EDITED:
Now I understand the problem better.
You are trying to call a python method from Parse.Cloud javascript based service. Based on their tutorials, I think you probably wanted the other way round.
Parse.Cloud allows you to deploy some server-side code in javascript. Then you can make REST API calls from your mobile app to the server endpoints by using either python or curl or any other language or tool. While testing, you can just call the end points from python on your box.
So your server code (in cloud/main.js) should look like this:
Parse.Cloud.define("testFunction", function(request, response) {
var excitedSentence = request.params.testString + "!!!";
response.success(excitedSentence);
});
This code creates a REST API endpoint at https://api.parse.com/1/functions/testFunction
Then you can call this API endpoint by using python (assuming you have Python installed on your box):
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/functions/testFunction', json.dumps({
"testString": "This is an example sentence"
}), {
"X-Parse-Application-Id": "xxxxx_PUT_YOUR_ID_xxxxxxx",
"X-Parse-REST-API-Key": "xxxxxxxx_YOUR_KEY_xxxxxx",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result
If you don't have python installed, you can call the API endpoint by going to the online dashboard.
Go to: Your App -> Core tab -> API Console.
For endpoint, select post (this is important), and specify "functions/testFunction" in the text box.
In request body, specify: {"testString" : "This is an example sentence"}
Click "Send Request" and you should see the following output:
"result": "This is an example sentence!!!"
I'm just following tutorials and figuring out how to handle get requests in NodeJS.
Here are snippets of my code:
NodeJS:
router.get('/test', function(request, response, next) {
console.log("Received Get Request");
response.jsonp({
data: 'test'
});
});
Angular:
$http.get("http://localhost:3000/test").
success(function(response) {
alert("OK");
}).
error(function(response) {
alert("FAIL");
});
If I try to access the link directly # localhost:3000/test, I'm able to receive the JSON message correctly. But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response)
SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of
the JSON data
The reason for that is because the response is empty but the response code is 200 in both cases.
I've tried searching for hours but maybe someone can enlighten me on this?
you could try and send
res.send('test')
and then on your http request you can use 'then'
$http.get("http://localhost:3000/test").then(function(res) {
console.log(res);
})
unlike success, then will give you a complete object (with 'test' - string as res.data)
success will bring you only the data;
then will bring you the whole object (with the status and such)..
now about that jsonp .. it's used to override a json response. you could simply use 'res.json({data: 'test'})' and it should also work for you..
hope it helps
You're using jsonp in node, which you probably don't need to. This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed)
Try changing the server to look like
response.json({
data: 'test'
});
If you look in the Network pane of the developer tools, you should be able to see the raw response. It should look something like:
{"data" : "test"}