NodeJS POST results in undefined - javascript

All my requests work perfectly except when I try to add an item to an array of json elements, it will return undefined every time.
Controller:
vm.addOptie = function () {
var newOptie = {"optie": 'stuur',"prijs": 150};
$http({
method: 'post',
url: 'http://localhost:3000/addGekozenOptie',
headers: {
'Content-Type': 'application/json'
},
data: newOptie
}).then(function (gekozenOpties) {
vm.gekozenOpties = gekozenOpties.data;
}).catch(function (err) {
alert('Er is een fout opgetreden: ' + err);
})
}
and my router/index.js
var router = require('express').Router();
var gekozenOpties = require('../public/data/opties.json');
router.post('/addGekozenOptie', function (req, res) {
var op = req.body;
gekozenOpties.push(op);
res.json(gekozenOpties);
});
module.exports = router;
Very frustrating seeing as everything else works fine (get/delete).

Have you tried the following?
//install body-parser
npm install body-parser
//Sample code within your app
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
if (!req.body) return res.sendStatus(400)
res.send('welcome, ' + req.body.username)
})
The bodyParser object exposes various factories to create middlewares.
All middlewares will populate the req.body property with the parsed
body, or an empty object ({}) if there was no body to parse (or an
error was returned).

Related

Importing json file from stackexchange and print using node js (express)

I'm trying to request the json file from stackexchange api and when the server loads save it on the client side so I can manipulate/change it locally.
I tried using this code but page just keep loading and nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res, next) => {
request(surl, (error, response, body) => {
// res.setHeader("Content-Type", "application/json; charset=utf-8");
res.json(body)
console.log('body:', body);
console.log('body:', req.body);
});
});
app.listen(3000, () => { console.log('On port 3000...') });
And if I comment out these two lines in my code below
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
It gives this kind of output.
"\u001f�\b��\u0000��8z00\u0000^{4���=�c��\u0000��#c�\u0002\u0000\u0000"
If anyone could give me a start that would be great! Thanks.
The output is gibberish because body is gzip compressed. It's not JSON, not even text:
To return it to browser, the easiest way is using pipe:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request(surl).pipe(res);
});
Or, if you want to manipulate/change the body, gzip: true option can be used:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request({
url: surl,
gzip: true
}, function(error, response, body) {
let bodyObj = JSON.parse(body);
// change bodyObj...
res.json(bodyObj);
});
});

How to fetch any API using URL by passing some value using form and get response according to form data from api

everyone, I am a beginner in nodejs and expressjs. So while practicing I got a question in my mind is that I am having one URL from where I want to fetch data and I simply did it.
Following is the code:
var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
app.set('view engine', 'ejs');
var urlencoderparser = bodyParser.urlencoded({ extended : true });
var data;
app.get('/', function (req, res) {
request.get('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json', function(err, res, body){
if(err) {
return console.log(error);
}
data = JSON.parse(body);
});
res.render('index', {data: data});
console.log(data);
});
app.listen(3000);
And this code is working fine.
Then I thought to change the URL by passing values using form.
we can enter a value in the form. The value should be either XML or JSON and according to that it will change the URL like the code given below:
var url = 'http://mysafeinfo.com/api/data?list=englishmonarchs&format='+form_data
Now for this, I tried request.post() in this way:
app.get('/', function (req, res) {
Request.post({
"headers": { "content-type": "application/json" },
"url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+form_data,
}, (error, response, body) => {
if(error) {
return console.log(error);
}
data = JSON.parse(body);
});
res.render('index', {data: data});
});
app.listen(3000);
But this is not working.
Please help me to know where I am wrong and whether this way is correct for coding in nodejs or expressjs?
Hello everyone i am adding whole code with you for more clearance
var express = require('express');
var app = express();
var request = require('request');
var bodyParser = require('body-parser');
app.set('view engine', 'ejs');
var urlencoderparser = bodyParser.urlencoded({ extended : true });
app.get('/', function(req, res){
res.render('index');
});
app.post('/', urlencoderparser, function(req, res){
res.render('form-data', {data : req.body});
request.post({
"headers": { "content-type": "application/json" },
"url": "http://mysafeinfo.com/api/data?list=englishmonarchs&format="+req.body.name,
}, (error, response, body) => {
if(error) {
return console.log(error);
}
data = JSON.parse(body);
});
console.log(req.body);
});
app.listen(3000);

req.cookies returns undefined but cookies are set

I am using cookie-parser in my express app. When the root page is requested I set a random number on the cookie using res.cookie(name, value) and it sets it fine (I checked on my browser console). But when I try to log req.cookie it always returns undefined.
Here's my code:
routes.js
var express = require('express')
var router = express.Router()
var movieTrailer = require('movie-trailer');
var Promise = require('bluebird');
var logs = require('log-switch');
var fs = require('fs');
//var cookieParser = require('cookie-parser');
//Setup x-ray for scraping
var Xray = require('x-ray');
var x = Xray();
var debug = false;
router.get('/', (req, res) => {
console.log('Page requested!');
console.log('Cookies: ', req.headers.cookies); // For some reason this returns undefined
var scrapeMovies = function(){
return new Promise((resolve, reject) =>{
fs.readFile('moviesRT.json', (err,data) =>{
var movies = JSON.parse(data);
resolve(movies);
});
});
};
scrapeMovies().then(
movies => {
var randomInt = Math.floor(Math.random() * movies.length);
res.cookie('randomInt', randomInt);
var randomMovie = movies[randomInt];
movieTrailer(randomMovie.title, (err, url) =>{
console.log('Requesting trailer: ', randomMovie.title);
if(err) throw err;
var embedUrl = url.replace('watch?v=','embed/');
console.log('Video ID: ', url.slice(32,url.length));
randomMovie.trailerURL = embedUrl; //Add the embed URL to the randomMovie object before rendering it
res.render('main',randomMovie,
(err, html) =>
{
if(err) throw err;
console.log('Rendering...');
res.send(html);
console.log("Done!");
});
});
});
});
module.exports = router;
app.js
const express = require('express');
//Define app and settings
const app = express();
const exphbs = require('express-handlebars');
var cookieParser = require('cookie-parser');
const port = 3000;
var routes = require('./routes');
var debug = true;
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
//app.use(cookieParser());
//View engine
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.listen(port, function () {
console.log(`Server Starts on ${port}`);
if(!debug) logs.disable(); //Disable logging if debug variable is false
});
You either want to check req.headers.cookie which will be set by express.
Or if you want to use the the parsed result of the cookie-parse middleware that is stored inreq.cookies then your problem is the order in which you register your routes and the middleware.
app.use('/', routes);
app.use(express.static('public'));
app.use(cookieParser());
The parsing of the cookie is done after the routes in routes have ben executed.
You need to move the cookieParser() before the route where you want to use it.
app.use(cookieParser());
app.use('/', routes);
app.use(express.static('public'));
This solved my problem:
Basically when you are sending a request to the server from client-side, make sure you add withCredentials: true. For example
{
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
'withCredentials':true
};
This happened to me, when I sent a PUT request from the client-side (Angular) without passing the body object.
I was doing this (second argument missing):
requestBranchEditPermission() {
return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, this.options).toPromise();
}
instead of this:
requestBranchEditPermission() {
return this.http.put<IPutProfile>(`${this.api}/some-endpoint`, {}, this.options).toPromise();
}
You will need to read the cookies as req.cookies['cookie-name'] and set the cookies as resInit.cookie('cookie-name', 'cookie-value')
This worked for me
in the frontend add credentials : 'include' as an option to your fetch API
A more elaborated code below for a get request
fetch('url', {credentials: 'include'})
.then(res => res.json())
.then(data => //do something with the data)
.catch(err => console.log(err.message));

Passing Angular variable to Express backend through POST

req.body is always empty. I'm not sure what I'm doing wrong? I tried adding content-type headers as json but that didn't do anything either. Can someone lead me in the correct direction please? Thank you
EDIT: just for clarification purposes, my Angular frontend hits the backend function successfully, but req.body is empty. If I understand everything correctly, if I'm using the 'body-parser' library, it should be passed in through post through 'req.body'. I'm just not seeing that though and I'm not sure why.
EDIT2: I have the body parser code in my app.js but the backend routing in a index.js file, does that have anything to do with it?
EDIT3: app.js http://pastebin.com/9vNgf0Nd
index.js http://pastebin.com/icLa3e2X
ANGULAR FRONTEND
service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {'Content-Type': 'application/json'}
});
}
BACKEND (app.js)
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
BACKEND (index.js)
var express = require('express');
var router = express.Router();
router.post('/register', function(req, res) {
console.log(req.body);
};
Please remove this line
app.use(bodyParser.urlencoded({ extended: true }))
Also,
app.use(bodyParser.json());
have to be called before app.use('/', routes);
And make sure to add Content-Type: application/json to the request header
What happens if you add the content type?
service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {
'Content-Type': 'application/json'
}
});
}
Try this
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/register', function(req, res) {
console.log(req.body);
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
and then execute this from prompt:
$ curl localhost:8081/register -v --data "{\"name\":\"test\",\"password\":\"hello\"}" --header "Content-Type: application/json"
this works for me!
There is nothing wrong in the UI code. Not sure what is router so you may try this or post the code for router.
Try this (this works for me) or you can also use your router:
app.post('/register', function (req, res) {
console.log(req.body);
res.send('welcome, ' + req.body.account.username)
});
You are missing:
var app = express();
app.use(router);
If you want to user routers refers to following example:
UPDATE with full code:
var express = require('express');
var router = express.Router();
var app = express();
app.use(router);
router.post('/register', function(req, res) {
console.log(req.body);
};
app.route('/register')
.post(function (req, res) {
console.log(req.body);
res.send('welcome, ' + req.body.account.username)
})

Node - Post request showing undefined

Im making a angular2/Node.js application. Right now when i try to get a object from the node server, it returns just fine. However, when i try to post data to the node server. The request.body shows undefined. What am i doing wrong ?
server.js
// Test
router.get('/test', function (req, res) {
res.json({test:true}); // Works
});
// Post
router.post('/rest', function (req, res) {
var body = req.body;
console.log(body); // Undefined
res.json({test:true});
});
app.ts
constructor(private http:Http){
console.log("Test")
http.get('/api/User/test').subscribe(result => {
console.log(result.json());
});
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post('/api/User/rest',{test:'Testing req'},{headers:headers})
.subscribe(result => {
console.log(result.json());
});
}
Did you install body-parser?
npm install body-parser --save
and before your routes, add it to your express application
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
see also: https://github.com/expressjs/body-parser

Categories

Resources