Node.js Express REST API - accessing JSON url params with GET request - json

I have a REST endpoint that is /geo/search and requires a number of long/lat coordinates to be sent as part of the request (GEO polygon).
Is there any way I can use JSON in the GET request? I was thinking that that URL encoding may be a solution:
var data = encodeURIComponent({"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]});
How would I access these params in the route?

Answer to #1 - thanks to #mccannf
Using JQuery.param:
Client:
var test = {"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]};
console.log($.param( test ));
Outputs:
coordinates%5B0%5D%5B%5D=-122.610168&coordinates%5B0%5D%5B%5D=37.598167&coordinates%5B1%5D%5B%5D=-122.288818&coordinates%5B1%5D%5B%5D=37.598167&coordinates%5B2%5D%5B%5D=-122.288818&coordinates%5B2%5D%5B%5D=37.845833&coordinates%5B3%5D%5B%5D=-122.610168&coordinates%5B3%5D%5B%5D=37.845833&coordinates%5B4%5D%5B%5D=-122.610168&coordinates%5B4%5D%5B%5D=37.598167
Answer to #2 - thanks to #Brad:
Server - Express route:
router.get('/search_polygon', function(req, res) {
console.log('Server received: ' + JSON.stringify(req.query.coordinates));
...
Outputs:
Server received: [["-122.610168","37.598167"],["-122.288818","37.598167"],["-122.288818","37.845833"],["-122.610168","37.845833"],["-122.610168","37.598167"]]
My issue was trying to pass these as part of the path, and not as parameters as they should be.

Related

Unable to access data inside a string (i.e. [ object Object ]) that was originally sent as a JSON object

I'm using axios to send a JSON object as a parameter to my api. Before it post request is fired, my data starts of as a JSON object. On the server side, when I console.log(req.params) the data is returned as such
[object Object]
When I used typeof, it returned a string. So then I went to use JSON.parse(). However, when I used that, it returned an error as such
SyntaxError: Unexpected token o in JSON at position 1
I looked for solutions, but nothing I tried seemed to work. Now I'm thinking I'm sending the data to the server incorrectly.
Here's my post request using axios:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/${mediaData}`)
return json;
}
Any thoughts on how I can solve this?
You need to update your code using axios to provide the mediaData in the body of the request instead of the URL:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/`, mediaData)
return json;
}
In the backend (assuming you're using express here), you need to configure your application to use bodyParser:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
And then in your controller update your console.log(req.params) to console.log(req.body); then restart your node server

Pretty print the JSON returned by express in Node.JS

I'm trying to follow this great design recommendation documentation for my server development in Node.JS regarding the JSON pretty formatting when returning it to the caller.
I can't figure out to do so when returning a file though:
app.get('/data.txt', function(req, res){
return res.sendFile(path.resolve(__dirname + '/views/myData.json'));
});
Would you have any suggestion?
You can simply require the JSON file using :
let fileContents = require(path.resolve(__dirname + '/views/myData.json'));
And then
app.get('/data.txt', function(req, res){
return res.send(fileContents);
});
Note: This approach doesn't send the file.It sends the contents of the JSON file in response.

POST request not able to find url

I am new to nodejs as well as developing.
I am trying to get a set of data bat from a nutrition site in JSON format. If I formulate the url with my app and api keys along with criteria to paste into the browser I get a JSON data ok. When I try to send a POST request as the site asks for when the request comes back it says it cannot find the url. What it is doing is attaching ':443' to the end of the host url and like I said coming back as an error:
Error: getaddrinfo ENOTFOUND https://api.nutritionix.com/v1_1/search https://api.nutritionix.com/v1_1/search:443
What I would like to do is after the end of the url is append the 'postData'.
Here is my code:
var https = require('https');
var querystring = require('querystring');
var postData = { // Nutrionix required JSON formt
"appId":"MY_APP_KEY",
"appKey":"MY_API_KEY",
"query": "Lentils",
"fields": ["item_name", "nf_calories", "nf_serving_size_qty", "nf_serving_size_unit"],
"sort":{
"field":"score",
"order":"desc"
},
"filters":{
"item_type":"2"
}
};
console.log("This is header dta" + postData);
postBody = querystring.stringify(postData);
var post_options = {
host:"https://api.nutritionix.com/v1_1/search",
"port":"443",
method:"post",
"path":"/",
headers:{"Content-Type":"application/json",
'Content-Length': postBody.length
}
}
console.log(post_options);
var request = https.request(post_options,function(response){
return response;
});
I also am passing this data into the dev HTTP add-on in Chrome and getting back the proper response.
Any help would be appreciated.
Can you please take a look at this documentation?
It seems that you don't need to mention HTTPS
Take the port off, 443 is the default for HTTPS.

Parsing Contentful Webhooks (Custom JSON types)

I'm currently using this Contentful-webhook-server to listen for webhooks when content is unpublished.
server.listen(30000, function(){
console.log('Contentful webhook server running on port ' + 30000)
});
server.on('ContentManagement.Entry.publish', function(req){
console.log('An entry was published!', req);
});
server.on('ContentManagement.Entry.unpublish', function(req){
console.log('An entry was unpublished!');
console.log('Deleted SOLR ID: ', req);
});
I'm trying to parse the response I've got but I can't seem to find a way to parse the custom JSON they use in their response. Should I be creating my own server with express or am I missing a way to get the response body in this example code.
The contentful-webhook-server library uses the plain node http module for the server. Thus, the req object is a readable stream that you need to buffer and parse to get the body.
Take a look at https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body for an example.

mocha - send json to post express route

I'm trying to send some json data to my '/sign_up' route in mocha test.
request = require 'supertest'
express = require 'express'
app = express()
Authentication = require("#{specDir}/../apps/authentication/routes")
authenticate = new Authentication app
Factory = require "#{specDir}/factories/user"
user = Factory.build 'user'
it 'creates an account', (done) ->
request(app).post('/sign_up').set('Accept', 'application/json').send(user).end (err, res) ->
expect(res.statusCode).to.equal 200
done()
However req.body in the callback function is undefined. Below I've shown a snippet of my route callback
#app.post '/sign_up', (req, res) ->
res.format
html: -> res.status(406).send 'invalid Content-Type'
json: ->
console.log req.body
res.status(200).send status: 'ok'
Probably I'm missing some small detail, but can't see what.. any ideas?
P.S. I'm well aware of that the tests pass and it does what it should, but before I move on to write more tests I gotta know how to send some data.
You're missing a body parser, add app.use(express.json()) in your code somewhere.