How do I get posted data from my api. I am using express 3.4.4
I am doing a resful api to accept posted data using node js and express
exports.mypost = function(req, res) {
console.log(req.body);
console.log(req.body.username);
console.log(req.body.name);
var user = new UserInfo({name:"dsd", username:"dsdsds"})
user.save();
res.send("user created");
}
and I post data use
curl --data "username=dsds&name=dsd" http://localhost:3000/mypost
I can see prints
{ username: 'dsds', name: 'dsd' }
dsds
dsd
But If I use
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I see
{}
undefined
undefined
which means I didn't catch username and name from
req.body
How do I get the data from
curl --form "username=dsds&name=dsd" http://localhost:3000/mypost
I am posting my app.js:
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var express = require('express');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
mongoose.connect('mongodb://localhost/data');
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var api = require('./controllers/api.js');
app.post('/mypost', api.mypost);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Add this:
App.use(express.bodyParser());
Make sure its set before all your routes.
You can use bodyParser method to get the data from a post request
// Configure server
app.configure(function() {
app.use(express.bodyParser());
}
Related
Every time I call: http://localhost:3000/api/tasks am getting a Cannot GET /api/tasks
My server.js
var express = require('express');
var path = require('path');
var BodyParser = require('body-parser');
var index = require('./routes/index');
var tasks = require('./routes/tasks');
var port = 3000;
var app = express();
//View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'client')));
// Body Parser MW
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: false}));
app.use('/', index);
app.use('api', tasks);
app.listen(port, function(){
console.log('Server started on port '+port);
});
I am still learning the ropes. Thank you in advance
tasks.js
var express = require('express');
var app= express();
var mongojs = require('mongojs')
var db = mongojs('mongodb://<user>.:<****>#ds125365.mlab.com:25365/mytasklist_wafalme', ['tasks'])
// Get All Tasks
app.get('/tasks', function(req, res, next){
db.tasks.find(function(err, tasks){
if(err){
res.send(err);
}
res.json(tasks);
});
});
// Get Single Tasks
app.get('/tasks/:id', function(req, res, next){
db.tasks.findOne({_id: mangojs.ObjectId(req.params.id)}, function(err, task){
if(err){
res.send(err);
}
res.json(task);
});
});
module.exports = app;
I have attached the task.js file that runs in the routes folder with the index.js
Use an absolute route to define the API routing context:
app.use('/', index);
app.use('/api', tasks);
Always include a forward slash (/) at the beginning of your routes.
I'm trying to follow this tutorial, in which the author provides a sample code:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
And I tweaked it a little bit and here is my code:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
var router = express.Router();
router.get('/', function(req, res, next) {
res.json({ message: 'Hello World!' });
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
The server runs perfectly but when I visit localhost:8081, I get the following message on my browser: Cannot GET /
What am I doing wrong here?
Since you added app.use('/api', router);
And your route is router.get('/', function(req, res, next) { res.json({ message: 'Hello World!' }); });
Then to access '/' you need to request with /api/
Update: If you have set the port on in env use that port or else you should be able to access using localhost:8081/api/
Hope it helps !
The above comment is correct.
You have added prefix '/api' to your local server and all incoming request will be http://localhost:<port>/api/<path>
app.use('/api', router);
If you want to access like this (without prefix) http://localhost:<port>/<path>
Please update your code to
app.use(router);
I have the follow - Generated initially by the Visual Studio Node Tools, uses Express and Jade as the client
/**
* Module dependencies.
*/
var express = require('express');
var fs = require('fs');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var https = require('https');
var path = require('path');
var passport = require('passport');
var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
var loginHandler = require('./routes/Login.js');
var auth = require('./config/auth.js');
var googleSupport = require('./googleSupport.js');
var googleAuthority = auth.googleAuth;
var googleScopes = '';
// retrieve google scopes
googleScopes = googleSupport.discoverServiceScopes(auth.googleAuth);
// set up passport
passport.serializeUser(function (user,done) {
done(null, user);
});
passport.deserializeUser(function (obj, done) {
done(null, obj);
});
passport.use(new googleStrategy({
clientID: googleAuthority.clientId,
clientSecret: googleAuthority.clientSecret,
callbackURL: googleAuthority.callbackUrl
},
function (accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));
var request = require('request');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
console.log('extracting service scopes');
app.get(passport.initialize());
app.get(passport.session());
app.get('/', routes.index);
app.get('/index', routes.index);
// google login support
// go to login page.
app.get('/googleLogin', passport.authenticate('google', { scope: [googleScopes] }),
function (req, res) {
res.redirect('/');
}
);
app.get('/AuthorizeGoogle', passport.authenticate('google', { failureRedirect: '/'}),
function (req, res) {
res.redirect('/');
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The thing is when it validates the user I get the following
500 Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\http\request.js:44:34)
at Strategy.module.exports.strategy.success (C:\Node\YourLivesN\YourLivesN\node_modules\passport\lib\middleware\authenticate.js:228:13)
at verified (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:179:18)
at Strategy._verify (C:\Node\YourLivesN\YourLivesN\app.js:41:12)
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\lib\strategy.js:195:22
at C:\Node\YourLivesN\YourLivesN\node_modules\passport-google-oauth\lib\passport-google-oauth\oauth2.js:115:7
at passBackControl (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:125:9)
at IncomingMessage. (C:\Node\YourLivesN\YourLivesN\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oauth\lib\oauth2.js:143:7)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
Now I am assuming this is the same cause as this question passport.js passport.initialize() middleware not in use but cannot see what order the calls should be in my code.
So can anyone tell me what order to place the various parts of the code.
Thanks
Try changing this part
app.get(passport.initialize());
app.get(passport.session());
to
app.use(passport.initialize());
app.use(passport.session());
further reading on subject : Difference between app.use and app.get in express.js
, and I would suggest you separate passport configuration in a stand alone file and require it on paths that need authentication. Example tutorial : https://www.youtube.com/watch?v=zbfet_-Z5UQ&index=12&list=PLZm85UZQLd2Q946FgnllFFMa0mfQLrYDL
I've been trying to debug my route in my express app. The request is undefined but not sure why.
I'm using Express 4.0 but running it Express 3.0 style (no bin/www).
server.js
var app = require('./app')
var port = process.env.PORT || 3000;
app.set('port', port);
app.listen(app.get('port', function(){
console.log('Express web server is listening on port ' + app.get('port'));
}));
app.js
var express = require('express'),
path = require('path'),
routes = require('./routes/index'),
app = express();
app.use('/', routes);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app;
routes/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
When I run debug on my app in webstorm, the page throws a 404 page not found. When I looked at the debug, here's the problem, the http request is undefined:
Make sure your app.listen... looks as follows
app.listen(app.get('port'), function() {
console.log('Express web server is listening on port ' + app.get('port'));
});
I'm new to Node.js. Trying to set up user account creation and log in using Passport. I can't ge it work. I am getting Unauthorized message although I am logging in with an existing user and pass. My code so far:
var express = require('express');
var http = require('http');
var path = require('path');
var request = require('request');
var app = express();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MongoClient = require('mongodb').MongoClient;
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(app.router);
app.enable('trust proxy');
if ('development' == app.get('env')) {
}
var httpserver = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');
/* Database has _id field but i guess i don't need to add anything here?*/
var Accoun = new Schema({
username: String,
password: String
});
/* Database collection is called 'users'*/
Accoun.plugin(passportLocalMongoose);
var Account = mongoose.model('users', Accoun);
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
mongoose.connect('xxxmyconnectionstring');
app.get('/', function(req, res) {
res.render('login.html');
});
app.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/myteam.html');
});
I need some expert help...
Regards,
I believe you need a successRedirect and failureRedirect in your app.post.