Json handling in angular $http post to express - json

I am trying to post json data to express server using angular $http,
$scope.createTravel = function(){
$http({
url: '/api/travels',
method:"POST",
data: $scope.formData
// headers: {'Content-Type': 'application/json'}
})
};
the post is reaching the server in this console log statement
app.post("/api/travels", function(req, res){
console.log(req);
});
without the json data.

Related

Node.js HTML response body

I am using the below code to post some JSON data to a url and in response I am getting a HTML page.
var request = require('request');
request.post({
url: "URL OF A WEBSITE",
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json:true
}, function(error, response, body){
console.log(error);
console.log(JSON.stringify(response));
console.log(body);
});
This code works fine I am getting a HTML page in the body tag.
I want to load that HTML page in the browser. How should I do that, I know this is a very basic question but I am very new to node.js someone please help me?
Follow the Express "Hello World" example and use your request call in the route handler:
/*jslint node:true, esversion:6*/
"use strict";
const request = require("request"),
express = require("express"),
app = express();
let my_json_obj = {},
URL_OF_WEBSITE = "http://www.google.com";
app.get("/", function (req, res) {
request.post({
url: URL_OF_WEBSITE,
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json: true
}, function (error, response, body) {
if (error) {
console.log(error);
return res.sendStatus(404);
}
console.log(JSON.stringify(response));
console.log(body);
res.send(body);
});
});
app.listen(3000, function () {
console.log("Example app listening on port 3000!");
});
node.js does have its own way to make a server, but for the sake of brevity and ease I just recommend using Express.
Are you using Express js? It would make things a lot easier when working with Node js apps.
Look into Express routing:
https://medium.com/javascript-scene/introduction-to-node-express-90c431f9e6fd
You can create an Express boilerplate in the terminal by using the command:
express yourappname
you can then put your html/css/js files inside the express-app -> 'public' folder that you just generated.
After that you create routes inside your app.js by doing something like:
// exampledomain.com/
// Loading the file index.html when user navigates to '/'
app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// or
// exampledomain.com/getFileURL
// POST request (from your ajax) to '/getFileURL'
// which will then load the about.html file into the browser
app.post('/getFileURL', function(req, res){
// Do more JSON/data handling & Node js stuff here then
// send something back
res.sendFile(path.join(__dirname + '/public/about.html'));
});
There're many more useful functions with Express js, but I think Routing is what you need right now.
p.s. Very useful tools to look into when working with Node js:
Postman (Testing ajax/express/Nodejs routes and responses)
Nodemon (Starting Nodejs server automatically on save)

How to receive (and decode) JSON from post data in Node.Js Express?

Suppose I have sent data with the following code:
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: transitions2,
success: function (data) {
},
dataType: "json"
});
where transitions2 is hierarchical JS object.
Now how can I receive it intact at server side
router.post('/save/:key', function(req, res) {
// where is my data here?
});
UPDATE
I found info about body parsers, and found that my site template already contained them. Particularly, app.js contains:
...
var bodyParser = require('body-parser');
...
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/data', express.static(path.join(__dirname, '../data')));
app.use('/', index);
...
So I wrote in my index.js:
...
router.post('/save/:key', function(req, res) {
var transitions = req.body;
image_data.save_transitions(req.params.key, req.query.postfix, transitions);
});
...
Unfortunately, transitions contains
while on client side it contained
i.e. was full of data.
What can be the problem?
UPDATE 2
I tried to do
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: JSON.stringify(transitions2),
success: function (data) {
}
});
and I see in Fiddler2 now, that full Json is passed.
[{"start_image":"20170402_1_NATURAL_COL0R","end_image":"20170409_1_NATURAL_COL0R","transition_classes":["no_transition","some_activity"]},...
Unfortunately, on server side I observe truncated and corrupted string
(equal sign should not be in JSON).
And JSON.parse fails.
use body-parser middleware to retrieve the data.
npm install body-parser
configure this in express app.
Find below the sample code
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Then in your router use the following:
router.post('/save/:key', function(req, res) {
var data = req.body // here is your data
});
The problem was on client side only. Correc way to post complex object with json is:
$.ajax({
type: "POST",
url: "/save/" + #{key},
data: JSON.stringify(transitions2),
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
stringify and contentType are obligatory.
front:
axios.post('/attack', {
number:number,
count:count
},
{
headers:{contentType: "application/json; charset=utf-8"}
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
back:
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
app.post('/attack', (req, res) => {
let data = req.body
console.log(data)
res.send('200')
})
console log: { number: '(number)', count: '(count)' }

nodeJS - make HTTPS request, sending JSON data

I would like to send an HTTPS POST from one nodeJS server to another. I have some JSON data I would like to send with this request (populated by a html form).
How can I do this? I am aware of https.request() but there does not seem to be an option to include JSON as a part of the query. From my research it seems possible with an HTTP request, but not an HTTPS request. How can I solve this?
const pug = require('pug');
var cloudinary = require('cloudinary');
var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var request = require('request');
var bodyParser = require('body-parser');
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'GET'
};
var app = express();
var parser = bodyParser.raw();
app.use(parser);
app.set('view engine', 'pug');
app.get('/', upload.single('avatar'), function(req, res) {
return res.render('index.pug');
});
app.get('/makeRequest*', function(req, res) {
query = req['query'];
/*
Here, I would like to send the contents of the query variable as JSON to the server specified in options.
*/
});
You can send JSON data through a POST http request with the native https node module, as stated in the documentation
All options from http.request() are valid.
So, taking the http.request() example you can do the following:
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = https.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
You should edit postData to your desired JSON object
I believe the below is what you want. Using the request library. See comments in the code for my recommendations.
...
var options = {
hostname: 'ec2-54-202-139-197.us-west-2.compute.amazonaws.com',
port: 443,
path: '/',
method: 'POST',
json: true
};
...
//making a post request and sending up your query is better then putting it in the query string
app.post('/makeRequest', function(req, res) {
var query = req.body['query'];
//NOTE, you cannot use a GET request to send JSON. You'll need to use a POST request.
//(you may need to make changes on your other servers)
options.body = { payload: query };
request(options, function(err, response, body) {
if (err) {
//Handle error
return;
}
if (response.statusCode == 200) {
console.log('contents received');
}
});
});
as matt mentioned you need to use request
to send JSON object not JSON.Stringify so that at the server you can receive it using:
app.post('/makeRequest', function(req, res) {
console.log (req.body.param1);
}
Use the following code:
var request = require("request");
request({
'url':"http://www.url.com",
method: "POST",
json: true,
body: {'param1':'any value'}
}, function (error, resp, body) {
console.log ("check response.");
});

Requesting a JSON using Request module (encoding issue) - Node.js

Im trying to request a Json file from a server different from mine but i cant set the right encoding.
I tried using HTTP module and failed.
Now im trying to do this using the 'Request' module.
The response i get is encoded to i dont know what. maybe utf 16 and is not readable at all.
Note: The json has some Hebrew chars in it.
I added the following to try and fix it but also failed:
headers: {'Content-Type': 'application/json; charset=utf-8'}
My code:
var http = require('http');
var request = require('request');
var express = require('express');
var app = express();
var url = 'http://www.oref.org.il/WarningMessages/alerts.json?v=1';
app.listen(process.env.PORT || 8080);
app.get('/', function(req,res){
res.send("Red color");
});
// get Alerts from web-service
app.get('/getAlerts', function(req,res){
request({
url: url,
json: true,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(response.headers) // Print the json response
res.set({
'content-type': 'application/json'
}).send(body);
}
})
});
That API returns a JSON response encoded in UTF-16-LE, so you'll have to tell request to use that encoding instead.
However, since you're trying to query Pikud Haoref's alerts API, check out pikud-haoref-api on npm to do the heavy lifting for you:
https://www.npmjs.com/package/pikud-haoref-api

Angular HTTP Post Request, Payload is nested in JSON Object

I am learning Angular and Node and I am trying to figure out how to have my Angular app hit a separate app hosting a rest API.
The request body is displayed as
{ '{"name":"test"}': '' }
and I expect it to be displayed as
{ "name" : "test"}
This is the front-end app that sends the post request.
$http({
method: 'POST',
url: 'http://localhost:8080/api/test',
data: {
"name": 'test'
},
dataType: "json",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
It is hitting the route defined as
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.post('/test', function(req, res) {
var name = req.body.name;
console.log(req.body);
});
I expect the issue to be with the content-type being application/x-www-form-urlencoded but I cannot figure out how to allow cors with application/json.
JSONP can be used for performing CORS requests (more about json/jsonp here What are the differences between JSON and JSONP?), and in AngularJS documentation - jsonp using $http