I want to use bodyParser on express. My posts.js file has
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.post('/', (req, res) => {
console.log(req.body);
});
module.exports = router;
On app.js file, the code is like
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const postsRoutes = require('./routes/posts');
// const usersRoutes = require('./routes/users');
app.use('/posts', postsRoutes);
// app.use('/users', usersRoutes);
Dependencies versions are
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.9.7",
"nodemon": "^2.0.3"
Server connected successfully but when I pass the data through postman on json mode, the terminal shows error like
SyntaxError: Unexpected token t in JSON at position 3
at JSON.parse (<anonymous>)...
I used the following code on app.js
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
because now express has buiild-in body-person function but output same here.
What can I do to solve this problem? I need help. Thanks in advance!
In JSON keys must be strings, try the following in the postman payload:
{
"title": "Title here",
"Description": "Description here..."
}
Instead of this:
{
title: "Title here",
Description: "Description here..."
}
Related
const express = require('express');
let router = express.Router();
router.get('/add-product',(req, res, next)=>{
res.send('<form action="/try" method="POST"><input type="text" name="title"><button type="submit">Sub,it</button> </form>');
});
package.json
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"funding": "^1.0.9"
It shows the error "unresolved function or method get()"
I even install express and body-parser
You should use express instead of express.Router()
let router = express();
If example will not help you please specify you app starting file
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
const routerProducts = express.Router()
// middleware that is specific to this router
routerProducts.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the add-product route
routerProducts.post('/add-product', function (req, res) {
res.send('products create')
})
// define the get-product route
routerProducts.get('/get-product', function (req, res) {
res.send('products get')
})
app.use('/products', routerProducts )
app.listen(3000, () => console.log('server started'));
call GET: http://127.0.0.1:3000/products/get-product
I am attempting to learn express and how to use postman and I'm following along a tutorial. Everything was going well until I tested router.get by sending dummy data to the server. I use postman to attempt to post to my localhost 500. Instead of getting a json back of the data in which I sent, I get a 200 status and nothing at the bottom of my screen. When i check the console upon hitting that route, this is logged to the console: http://undefined/api/members.
Mind you, I have no trouble using router.get to receive a json of all my members and I have no trouble receiving a json by searching with just the member ID. But for whatever reason router.post isn't working for me. I suspect this has to do with the body parser. But I'm not sure why specifically it isn't working. Please help.
This is how I set up my app file:
const express = require('express')
const app = express()
const path = require('path');
const logger = require('./middleware/logger')
const bodyParser = require('body-parser')
app.use(logger)
app.use('/api/members', require('./routes/api/members'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(express.static(path.join(__dirname, 'public')))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${[PORT]}`)
})
The following is how I set up my router file
const express = require('express')
const router = express.Router()
const members = require('../../Members')
router.get('/', (req, res) =>{
res.json(members);
})
router.get('/:id', (req, res) => {
const found = members.some(member => member.id === parseInt(req.params.id));
if(found){
res.json(members.filter(member => member.id === parseInt(req.params.id)))
} else {
res.status(400).json({msg: `No member with the id of ${req.params.id}`})
}
})
router.post('/', (req, res) => {
res.send(req.body)
})
module.exports = router
my package.json:
{
"name": "expressCrashCourse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"moment": "^2.24.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
Routes are processed in order so if you want the body-parser middleware to be active for your .post() route, the middleware has to be BEFORE it. So, change this:
app.use('/api/members', require('./routes/api/members'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
to this:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use('/api/members', require('./routes/api/members')) // <== after your middleware
As it was, it was hitting your route before the middleware got a chance to run and thus req.body was still not populated with the body contents.
I'm still trying to understand routing in node.js,
Other routes like route.get(all) and single id are working perfectly, but "router.post" is giving an error in postman such as "TypeError: Cannot read property email of undefined";
For the index.js
const express = require('express');
const redflags_table = require('../db/redflags_table');
const router = express.Router();
router.put('/api/v1/redflag/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
let recordFound;
let itemIndex;
redflags_table.map((record, index) => {
if (record.id === id) {
recordFound = record;
itemIndex = index;
}
});
if (!recordFound) {
return res.status(404).send({
success: 'false',
message: 'todo not found',
});
}
if (!req.body.email) {
return res.status(400).send({
success: 'false',
message: 'title is required',
});
}
const updatedRedflag = {
id: recordFound.id,
email: req.body.email || recordFound.email
};
redflags_table.splice(itemIndex, 1, updatedRedflag);
return res.status(201).send({
success: 'true',
message: 'todo added successfully',
updatedRedflag,
});
});
The app.js:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = require('./routes/index.js');
app.use(router);
app.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json())
Rearrage the order of your middleware.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = require('./routes/index.js');
app.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json())
app.use(router);
UPDATE 2021
Now body-parser is deprecated, you can use express:
import express from 'express'
const app = express()
app.use(express.json({limit: '20mb'}))
app.use(express.urlencoded({ extended: false, limit: '20mb' }))
export default app
If you are using Mongoose then it can be solved by fixing options .like this mongoose.set('useFindAndModify', false);
Hopefully your problem will be sorted .
You can fix this with these simple steps.
install body parser for content-type - application/x-www-form-urlencoded
1) npm i --save body-parser
2)go into your root file in your case it is index.js add these lines of code before routes.
//require body-parser
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))
I am new to node js and following a tutorial on scotch.io. I've imported morgan for logging requests, but when I run the code I get TypeError: app.use is not a function. This is my code for app.js;
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express;
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to deep thinking.'
}));
module.exports = app;
And for package.json:
{
"name": "postgres-express-react-node-tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start:dev": "nodemon ./bin/www",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.3",
"morgan": "^1.9.1"
},
"devDependencies": {
"nodemon": "^1.18.4"
}
}
require('express') returns a function, which you should call in order to get the express application. Therefore:
const app = express;
should be changed to:
const app = express();
Try this, change app=express; to app=express();
const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express(); // changed this line
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to deep thinking.'
}));
module.exports = app;
When calling API https://mywebsite.com/api/register through browser and it returns correct response from server as { "error": false, "message": "Hello World" }
If we hit the same request from postman then it returns with some html content as Please enable JavaScript to view the page content.
Below is node side code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', "extended": false }));
router.get("/", function (req, res) {
res.json({ "error": false, "message": "Hello World" });
});
The api working through the browser but not with postman. What will be the possible errors?
If you want to separate the router files then use the following pattern otherwise use app.get()
app.js
var express = require('express'),
car = require('./routes/car'),
bus = require('./routes/bus');
var app = express();
app.use('/car', car);
app.use('/bus', bus);
app.listen(2000);
car.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('GET handler for /car route.');
});
router.post('/', function(req, res) {
res.send('POST handler for /car route.');
});
router.put('/', function(req, res) {
res.send('put handler for /car route.');
});
module.exports = router;
Try this instead:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', "extended": false }));
app.listen(8080);
app.get("/", function (req, res) {
res.json({ "error": false, "message": "Hello World" });
});
Replace router.get with app.get.
I test your code on my browser and it doesn't work too.