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);
Related
Very new to express and file system and don't have much idea about directories so getting this error.
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
app.use('/public',express.static(__dirname +"/public"));
Getting error "Cannot GET /public/signup.html"
My directories is:
-Express
--Server.js
--public
---signup.html
Looks like your code is a little jumbled up. Separate out your port listener - this should always come last. Add your routes and middleware before that as individual calls to app, and also register your get request to redirect back to your server to the signup html.
This should work:
var express = require("express");
var path = require("path");
var port = 2121;
var app = express();
// Register Middlewares/Headers
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Register Static
app.use("/public", express.static(__dirname + "/public"));
// Register redirect
app.get('/', (req, res) => {
res.redirect(req.baseUrl + '/public/signup.html');
});
app.listen(port, () => {
console.log("server Running on : ", port);
});
You're calling listen on app before you call use on your middleware and there are a few mistakes in your code. I think this should work:
app
.use('/public',express.static(`${__dirname}/public`))
.get('/', (req, res) => {
res.header({
'Access-control-Allow-Origin': '*'
});
res.redirect(`${req.baseUrl}/public/signup.html`);
})
.listen(2121);
You should provide
app.use('/public',express.static(__dirname +"/public"));
Before you using app.get
Full example:
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.use('/public',express.static(__dirname +"/public"));
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
I'm currently writing a web application with the MEAN stack, and am testing to see if my nodejs server is working. Here's my server.js:
// server.js
'use strict';
// modules =================================================
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
// expose app
exports = module.exports = app;
I currently have it redirecting all routes to my index.html file to test to make sure my views are working. Here's my routes.js:
// models/routes.js
// grab the user model
var User = require('./models/user.js');
module.exports = {
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
However, when I try to run node server.js, it gives me this error:
/home/hess/Projects/FitTrak/app/routes.js
app.get('*', function(req, res) {
^
SyntaxError: Unexpected token .
Does anyone have any idea what's causing this? I checked and all my braces and parentheses are all closed and written correctly.
As Jose Hermosilla Rodrigo said in his comment, you're declaring the object literal module.exports wrong. It should look like this instead:
module.exports = function(app) {
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
just try this code...
// models/routes.js
var express=require('express');
var app=express();
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
module.exports = route;
server.js
'use strict';
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var route=require('./models/route.js');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
app.use('/',route);
If you are using MEAN stack I would suggest you to use express own router middleware to handle all your routes. Just include.
var router = express.Router();
//use router to handle all your request
router.get(/xxx,function(req, res){
res.send(/xxxx);
})
// You may have n number of router for all your request
//And at last all you have to do is export router
module.exports = router;
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
oracledb.autoCommit = true;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
router.use('/' , function(req, res , next) {
console.log('Something is happening.');
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/insert')
.post(function(req, res) {
console.log(req.body);
console.log(req.body.c1);
console.log(req.body.c2);
});
app.use('/api', router);
app.listen(port);
In the example above ,when I try to log req.body it is returned as empty along with any of its properties.
EDIT: Maybe unrelated but when I try to test this REST API with a extension like Postman , it just keeps processing indefinately. ( Same thing happens with extension called DHC Rest)
i'm having an issue where a user disconnects from socket.io and the instances remains active, including all event listeners.
Both examples below is partial code of my progress due to hundreds of rows. But the issue remains with this code.
app.js example:
var express = require('express'),
app = express(),
routes = require('./routes/index'),
server = require('http').createServer(app);
io = require('socket.io').listen(server);
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.use('/', routes);
server.listen(3000, function() {
console.log('listening on *:3000');
});
module.exports = app;
index.js route example:
var express = require('express'),
router = express.Router();
router.get('/', function(req, res) {
res.render('home', {
title: 'Home'
});
setupSocket(req);
});
function setupSocket(req) {
io.on('connection', function(socket) {
console.log('connected')
});
}
module.exports = router;
This will result in:
First connection:
connected
Second connection:
connected
connected
Third connection:
connected
connected
connected
And so on. This will continue on page reload, in a new tab, in a new browser or anything else until i restart the node server.
In my code i'm posting data from client side to a mongo database and due the the issue above, the request will post multiple copies of the same data.
So the question is, how do i prevent the instance to remain active after a user has left the page?
As you said on every connection or refresh you are getting multipleconnected strings outputs, that's because you are attaching socket.io listeners on each request. This is how you should attach the connected listener on your socket.io:
var express = require('express'),
app = express(),
routes = require('./routes/index'),
server = require('http').createServer(app);
io = require('socket.io').listen(server);
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');
app.use('/', routes);
// Your listener should be outside your routes
io.on('connection', function(socket) {
console.log('connected')
});
server.listen(3000, function() {
console.log('listening on *:3000');
});
module.exports = app;
And on your index.js just remove the setUp function:
var express = require('express'),
router = express.Router();
router.get('/', function(req, res) {
res.render('home', {
title: 'Home'
});
});
module.exports = router;
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());
}