I a beginner following a nodejs tutorial.
From said tutorial, I generated the following code:
[Index.js]
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var cats = require('./cats.js')(app);
var server = app.listen(3000, function(){
console.log('Server running at http://127.0.0.1/3000');
});
[Cat.js]
var _ = require('lodash');
module.exports = function(app){
_cats = [];
/*
Create
*/
app.post('/cat', function(req, res){
console.log('Testing: ' + req.body);
res.json({info: 'Cat created successfully!'});
});
/*
Read
*/
app.get('/cat', function(req, res){
res.send(_cats);
});
.
.
.
.
When I start the node script, and post some json cat data as described in the tutorial, my web browser displays empty json brackets for each json input I made.
Can anyone tell me what I missed or I'm doing wrong? Why do I get empty JSON brackets instead of my cat data printed out?
I'm an utter newbie at NodeJS so I apologise if I have not described issues adequately.
UPDATE:
I'm using the Postman Chrome extension to POST json, {'name':'sam','age':'1','type':'alley'} to http://localhost:3000/cat.
The tutorial I'm following is on PluralSight. I don't think it's accessible without an account but they do offer a couple of days free to get you started.
Take a look at this working sample:
var express = require('express');
var app = express();
var cats = [];
var counter = 1;
app.post('/cat', function (req, res) {
cats.push({id: counter, name: 'Jacklyn'});
counter++;
res.json({info:'cat created successfully'});
});
app.get('/cat', function(req, res) {
res.json(cats);
});
app.listen(8888);
You need to send at least one POST request in order to have a cat in the array and after each new POST request the amount of cats will increase.
It's because the code you posted does not update the _cats array. The code for post handler should be:
app.post('/cat', function(req, res){
console.log('Testing: ' + req.body);
_cats.push(req.body); // This is the missing line
res.json({info: 'Cat created successfully!'});
});
Here I assume that the body contains a single object and it is already parsed. If not, you can add required manipulations...
Edit
It seems that the request body should be parsed. The express framework has an additional module, the body-parser, which is used for this purpose:
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // this will parse json requests
For more information, see bodyParser on GitHub.
Related
Just want to display my node.js result on web browser..
is it possible?...
here's my code:
const testFolder = 'texts/';
const fs = require('fs');
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
})
when I try to run that code on cmd it works. The code gets all the .txt file on a specific directory.
here's the result:
then when i tried to load it on my browser the result goes like this
Im also planing to add all the result filename to database mysql once the node.js code fixed.. is that also possible?..
thank you.. this is my first time to create a node.js
Use the express router to accept GET request from your browser :
const express = require('express');
const fs = require('fs');
const app = express();
const testFolder = 'texts/';
// To set your public directory and use relative url
app.use(express.static(__dirname + 'your_public_dir'));
// When you access to localhost:8080, it will send GET '/' request
app.get('/', function(req,res) {
fs.readdirSync(testFolder).forEach(file => {
console.log(file);
});
});
Nicolas is right, express can achieve this. Just remember to install it using NPM, this can be done by executing following command under the directory where package.json is:
npm install --save express
however, you would also need to write into response of the server so it shows on website. So for example, using Express:
app.get('/', function(req,res) {
res.write("whatever you want to display");
res.end()
});
I'm writing a relatively new app and was wondering which I should use:
express.json()
or
bodyParser.json()
Can I assume they do the same thing.
I would like to just use express.json() as it is built in already.
Earlier versions of Express used to have a lot of middleware bundled with it. bodyParser was one of the middleware that came with it. When Express 4.0 was released they decided to remove the bundled middleware from Express and make them separate packages instead. The syntax then changed from app.use(express.json()) to app.use(bodyParser.json()) after installing the bodyParser module.
bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express like before. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.
The release history for 4.16.0 is here for those who are interested, and the pull request is here.
YES! Correct
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Yes both are same .
if you go into the file node_module/express/lib/express.js
you can see under module dependencies body parser module is already imported
/**
* Module dependencies.
*/
var bodyParser = require('body-parser')
//other modules
the objects and methods inside bodyparser module are accessible as they are exported using the special object module.exports
exports = module.exports = createApplication;
exports.json = bodyParser.json
this is accessible from express object just by calling
express.json()
Yes!! you can use both of them. However, since express.json() is now already built into express, it is wiser to use express.json() than the bodyParser.json().
Yes!! Due to the widespread opinion of the people to integrate body-parser back with the express, the latest release does exactly this. You should be right to assume that both perform the same tasks, that is to recognize incoming request object as JSON objects. Feel free to use either.
Mean server with angular 2+.
I have a dataservice.js that requests a get to the server, to receive a json response from the http://localhost:3000/server/routes/api/test.js
This gives me an error 500 view engine not selected,
My understanding is angular doesn’t require a view engine? As the angular/ browser takes care of that.
Somehow the routing doesn’t seem to work when I do a getter to the api.
The angular routes work with the html components, but via the dataservice a get request to the mongodb doesn’t work either. The get/test most often returns error 500 no view engine selected as well.
If it does return something, it returns an error message “<“ not in jsn format.
How do I make sure that the routing works for my get and post messages and they are returned back in json format and not in HTML.
And how do I figure out that it uses the correct routing? I somehow doubt that the rouitng for the get/ post messages seem to use express rather then the angular modules
I am quite new to stack overflow/ Mean server so if you require more info please let me know.
FYI
I have been able to get a json file from the server (not the database) via a get. This worked. So why is it that a get to the database doesn’t seem to work and the same question about why I can’t seem to get a json response from the http://localhost:3000/server/routes/test/api.js in the api.
I spent a full 2 days troubleshooting to no result.
in my api.js
router.get ('/test', function (req, res, next) {
res.json({'testMessage': 'everything is going ', 'someNumber': 457});
});
In the server.js
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require ('morgan');
var mongoose = require('mongoose');
var flash = require('connect-flash');
var chat = require('./server/routes/chat');
var app = express();
var passport = require ('passport');
var cookieParser = require ('cookie-parser');
var session = require ('express-session');
var config = require ('./config/database');
var engines = require('consolidate');
var mongoose = require('mongoose');
var router = express.Router();
// this is where I set up the routing for the api
// in the root of the project I created server directory and
// within it a routes directory that holds the api.js
var api = require('./server/routes/api');
mongoose.Promise = require ('q').Promise;
require('./config/passport')(passport);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(morgan('dev'));
app.use(session({
secret: 'secret123',
resave: true,
saveUnitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//this is where I set up the routing is something wrong here?
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use('api', api);
thx everyone, I moved
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
below
app.use('api', api);
and changed it to:
app.use('/api', api);
Problem solved, if app.get('*') is read first it will send all requests to index.html instead. So make sure any other routings go above it.
I was following instructions to build a RESTful API with Express and MySQL(*1)
But when I change
app.listen(port); //excutable, GET returns welcome message
into
orm.initialize(WConfig.config,function(err,models){
...
in the part 2 of(*1), which is adding MySQL information into server.js,
I gets the following on Node.JS command prompt:
TypeError: Cannot read property 'bear' of undefined
Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated.
full code of server.js:
// server.js
var util = require('util');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Waterline = require('waterline');
var Bear = require('./app/models/bear');
var WConfig = require('./app/config/waterline');
var orm = new Waterline();
orm.loadCollection(Bear);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hello! welcome to our api!' });
});
app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead
router.route('/bears')
.post(function(req,res) {
app.models.bear.create(req.body,function(err,model) {
if(err) return res.status(500).json({ err,err });
res.json(model); //res.json(model) , guess: res.status(200).json(model);
console.log(util.inspect(model));
});
});
//gets error if I change it to following
//
orm.initialize(WConfig.config,function(err,models){
if(err) throw err;
app.models = models.collections;
//app.set('models',models.collections);
app.connections = models.connections;
app.listen(port);
console.log('Magic happens on port ' + port);
});
reference:
1.Create Restful API with Express and waterline (in Chinese)
https://segmentfault.com/a/1190000004996659#articleHeader2
2.Build a RESTful API Using Node and Express 4
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
After a lot of fiddling with upgrading versions and the different middleware/ways of using a body parser, I am still stuck.
I have an Iphone app which POSTs 2 things (2 separate things). First is an image, which works.
Second is a json object which i try to put into mongodb.
No matter what i do, i can't seem to log the contents of the request.
var express = require('express');
var logger = require('morgan');
var fs = require('fs');
var json = require('express-json');
var path = require('path');
var errorHandler = require('errorhandler');
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
FileDriver = require('./fileDriver').FileDriver;
...
app.use(json());
//app.use(bodyParser.urlencoded({ extended: true }));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
...
app.post('/:collection', function(req, res) {
console.warn(req.body.poi.toString());
var object = req.body;
var collection = req.params.collection;
console.warn("Post: " + req.toString());
collectionDriver.save(collection, object, function(err,docs) {
if (err) { res.send(400, err); }
else { res.send(201, docs); }
});
});
I've tried logging (log, warn) req.body, req, etc. to no avail.
i'm using express-json and NOT url encoding, don't think need it.
morgan ouputs the following when i post
POST /pois 200 15.983 ms - 63
and nothing else!
It apparently cannot do it, as stated in this closed issue https://github.com/expressjs/morgan/issues/16
morgan is not intended for this kind of work. Try and use Winston instead, or simply console.log
This does it for me:
const express = require('express')
const app = express()
app.use(express.json())
var morgan = require('morgan')
morgan.token('response-body', (req, res) => {return JSON.stringify(req.body)}); // define 'response-body' token using JSON.stringify
app.use(morgan(':method :url :response-time :response-body')) //include newly defined ':response-body' token
app.post(/....)