I am trying to parse the json object sent in the request and echo out the data being sent
Here is my post request
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
name:"Bob"
}),
// processData: false, // this is optional
dataType: 'json'
});
Here is how I am trying to access the object parameters
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', router);
app.listen(8010);
router.post('/addUser', function(req, res){
console.log(req.body);
});
I think you need :
router.post('/addUser', function(req, res){
console.log(req.body.name);
});
EDIT
After testing it, you also miss these two lines (or you didn't include them on purpose) :
app.use(router); //You need to register your rooter as a middleware
app.listen(1234); //Your port of choice
The key here is the fact that you use the middleware 'body-parser'.
What it does is simple, it parses the data and creates a body object as a parameter of your request.
Therefore, the name parameter you're looking for will be found in : req.body.name and not in param
Quote from the github page :
req.body
A new body object containing the parsed data is populated on the request object after the middleware.
Related
So the body of my Angular post request is empty on my server. The post request from my client application is:
var data = {
Stime: '+this.Stime+',
Etime: '+this.Etime+',
eAMPM: '+this.eAMPM+',
sAMPM: '+this.sAMPM+',
id: '+this.id+',
activity: '+this.activity+',
auto_insert: '+this.auto_insert+',
yearmonthday: '+this.yearmonthday+',
color1: '+this.c+'
}
this.$http({
method: 'POST',
url: 'http://localhost:3000/operation',
data: JSON.stringify(data)
})
before I tried using this post request I just had a very long query string and this passed the data just fine. But I am cleaning up my code now and this way isnt working.
On my server I have:
app.post('/operation', function(req,res){
console.log(req.body); //prints {}
res.send("inserted");
});
Also on the server side I have
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
multer = require('multer'),
jsonParser = bodyParser.json()
app.use(jsonParser)
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Inside app.post(...) {} you need to wait for data to become available like this:
var body = '';
req.on('data',function(data) { body += data; });
req.on('end', function(data) {
req.body = JSON.parse(body);
conosle.log(request.body);
});
I'm quite new to AJAX, so sorry for potential missunderstandings, but I'm not completely through that thing.
I'm trying a simple thing. I have a server.js file, which is my backend basically. Then I have a index.html and a script.js. That's all, so a very basic setup. Now, on my script.js, I'm getting some data (a mail address). Now I want to send that data to my backend (into the server.js) to work with it there. How can I do this?
I found some posts already about AJAX with node.js, but I don't get it, especially not where to receive it in my backend. I'm using express for the server by the way.
What I have in my script.js is:
$.ajax({
type: "POST",
url: "server.js",
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
Right so far? How can I now receive the information in my server.js?
There's not much in so far, just:
var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
Thanks for any help :)
Note: This was written before the question was updated with the code so the field names and port numbers that I used here as examples may need to be updated with the correct values.
Client-side code - example with jQuery:
$.post('/email', { address: 'xxx#example.com' });
(this can take optional callbacks and it returns a promise that can be used to add a success/error handler)
Server-side code - example with Express:
const express = require('express');
const bodyParser = require('body-parser');
const dir = path.join(__dirname, 'public');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/email', (req, res) => {
// you have address available in req.body:
console.log(req.body.address);
// always send a response:
res.json({ ok: true });
});
app.use(express.static(dir));
app.listen(4443, () => console.log('Listening on http://localhost:4443/'));
This assumes that your static files (HTML, client-side JavaScript, CSS) are in the public directory relative to your server.js file.
See this for background on the JSON/form-encoding issue:
Which method is prefer when building API
See this for background on serving static files:
How to serve an image using nodejs
That's actually quite simple to implement in Express.JS with the basic router:
I'm gonna give you the minified code snippets to help you get sense of how it works across browser and server.
in Front-End, you basically just want to "post" an email address to the backend:
$.post('/email', { email: 'howareyou#xx.com' })
and in Back-End(Express.JS), you should implement the basic router:
var express = require('express');
var app = express();
// use: app.METHOD(PATH, HANDLER)
app.post('/email/', function(req, res) {
var email = req.body.email
})
Read more here: http://expressjs.com/en/guide/routing.html
First, you need a valid route to hit when the server is running. You can do this in server.js through express.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
app.post('/mail', function(req, res) {
var body = req.body;
console.log('email', body.email);
res.json({ message: 'I got the email!' });
});
var server = app.listen(3000);
Notice I have brought in an express middleware that will parse the body for JSON and make it available on the req object under req.body. You will need to install this dependency with npm install --save body-parser.
Then you need to send a POST request to that URL from the front-end.
$.ajax({
type: "POST",
url: "/mail",
data: { mail: mail },
success: function(data) {
console.log('message', data.message);
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
Now, if you submit an email, you should see a log in your terminal that shows the email and a log in your developer console in the browser that shows the message "I got the email!"
in server.js add this :
app.post('/searching', function(req, res){
//do something with req
});
and in script.js :
$.ajax({
type: "POST",
url: "/searching",
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
First of all you nedd to create a route for the Mail
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var router=app.Router();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); // Parse request body
app.use(express.static(path.join(__dirname, 'public')));
// Route to check Email
router.post('/CheckEmail',(req,res)=>{
var email=req.body.mail; // Get email here
})
app.listen(process.env.port || 3000,()=>{
console.log('server is running');
})
Ajax
$.ajax({
type: "POST",
url: "/CheckEmail", // post route name here
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
You need a few more things to actually be able to parse the body. Add this to your server.js file.
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
You need to specify a valid URL. Since you are listening on 3000. You also need to specify a route on your server as an endpoint.
$.ajax({
type: "POST",
url: "http:localhost:3000/",
data: { mail: mail },
success: function(data) {
},
error: function(jqXHR, textStatus, err) {
alert('text status '+textStatus+', err '+err)
}
});
Now you need to add a route on your server. You can do so by adding this to your server.js file after all of the app.use calls
app.post("/", function(req, res){
// your logic here
res.send("I am sending something back!");
})
I am making an Ajax request that looks like this:
$.ajax({
url: '/gen',
type: 'POST',
data: JSON.stringify({'one': 1, 'two':2}),
success: function(data) {console.log(this)}
});
and my express portion looks like this:
var express = require('express');
var app = express();
var router = express.Router();
app.set('port', (process.env.PORT || 5000));
router.post('/gen', function(req, res) {
console.log(req.body);
});
this always outputs undefined in the console.
How can I change this around to make the req.body, or any part of the req, contain the information I am trying to send over to the express portion of the code.
You need to use the body parser.
var bodyParser = require('body-parser')
app.use(bodyParser.json());
See:
https://github.com/expressjs/body-parser
You may also need to add:
contentType: 'application/json',
in your .ajax() options.
To use use req.body you have to use the bodyParser middleware, import it like this:
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json());
router.post('/gen', function(req, res) {
console.log(req.body);
});
Below are my Server's code
/* GET tone. */
router.post('/tone', function(req, res, next) {
console.log("what is the body" + req.body.data);
tone_analyzer.tone({ text: req.body.data }, function(err, tone) {
console.log(req.body.data);
if (err) {
console.log(err);
} else {
res.send(JSON.stringify(tone, null, 2));
}
console.log(req);
});
});
My Ajax's call in the html page.
function toneAnalysis(info){
$.ajax({
url: 'http://localhost:3000/tone',
type: 'POST',
data: info,
success: function(res) {
console.log("testing " + info);
},
error: function(xhr, status, errorThrown) {
console.log(status);
}
})
The server could not retrieve the req.body.data. When I tried to console log it, it always prints undefined. Could any one help me out with this? Thank you.
Update:
The printed req.body after I used body parser
Like the answer above mentioned you can use BodyParser and you can download it and install it using npm like so:
# npm install bodyparser --save
Then returning to your $.ajax call, you are sending some data represented in the data object, so using the BodyParser you can simply have an access to the sent object, because BodyParser add another object to the req nodejs object and it's called body, so if you want to access to all sent items using BodyParser you will probably going to do it like so :
const app = require('express')();
let bodyParser = require('body-parser');
// add a new middleware to your application with the help of BodyParser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//Configure the route
router.post('/tone', (req, res, next) => {
console.log("what is the body" + req.body.data);
tone_analyzer.tone({ text: req.body.data}, (err, tone) => {
console.log(req.body.data);
if (err){
console.log(err);
}
else{
res.send(JSON.stringify(tone, null, 2));
}
console.log(req);
});
});
Now using BodyParser, things can get really easy when you handle your XHR or HTTP calls.
your request body will be in req.body
if it is json you can use
let bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
router.post('/tone', function(req, res, next) {
console.log("what is the body" + req.body);
tone_analyzer.tone({ text: req.body},
function(err, tone) {
// your code here
}
Do you have this in your server configuration?
app.use(express.bodyParser());
This allows you to parse JSON requests.
I am trying to build a simple Node.js app which will parse data passed to it as POST requests from my AngularJS app. Below is the code used in my AngularJS app and my Node.js app. Problem I am facing is that I've searched the web trying to find how to parse (data and header) information passed in POST requests but failed to find any example, so any help with an example of parsing (data and header) passed in POST requests will help me a lot. Thanks.
Note: I am using express 4.1.2, body-parser 1.8.0.
Node app:
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.post('/', function (req, res) {
console.log(req.body);
res.send(200);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
POST request code
var deferred = $q.defer();
var dataObj = {};
dataObj.name = 'Chan';
dataObj.email_address = 'email#domain.com';
var myToken = '1234567890';
$http({ method:'POST',
url: '/',
data: dataObj,
headers: { 'Token' : myToken
}
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
return deferred.promise;
If you're setting data to a plain js object, angular is interpreting that as a urlencoded form with the various keys and values in that object.
So there's two possible fixes here. One is to add something like app.use(bodyParser.urlencoded({ extended: false })); after app.use(bodyParser.json());
The second possible fix is to change your $http call to post JSON instead of urlencoded data. For that, change data: dataObj, to data: JSON.stringify(dataObj), and add 'Content-Type': 'application/json' to your headers so that it looks like this:
headers: {
'Token' : myToken,
'Content-Type': 'application/json'
}