Node.js Express Can't get Post Data - node.js

When I post to /insertUser and it schema.saveUser(req) it doesn't find the correct data. I am using node-inspector and it can't find my post data. I have also tried req.body and it finds nothing. I am sending a json
var express = require('express');
var bodyParser = require('body-parser');
var schema = require("./schemas");
var app = express();
app.get('/hello.txt', function(req, res){
res.send('Hello World2');
});
app.post('/insertUser', function(req, res){
console.log("Request handler 'insertUser' was called.");
//console.log(req.body);
schema.saveUser(req);
response.writeHead(200, {"Content-Type": "text/plain"});
res.send("You've sent the text: " + req);
response.write("The following data has been saved to the database: " + jsonString);
res.end();
});
var server = app.listen(8888, function() {
console.log('Listening on port %d', server.address().port);
});
function saveUser(postData){
var jsonObj = JSON.parse(postData);
var newUser = new User({
name: jsonObj.name,
email: jsonObj.email,
photoURL: jsonObj.photourl,
groups: jsonObj.groups
});
newUser.save(function(err, newUser) {
if (err) return console.error(err);
console.dir(newUser);
});
}
edit:
SyntaxError: Unexpected token o
at Object.parse (native)
at Object.saveUser (schemas.js:42:22)
at Object.handle (server.js:25:9)
at next_layer (route.js:103:13)
at Route.dispatch (route.js:107:5)
at c (index.js:195:24)
at Function.proto.process_params (index.js:251:12)
at next (index.js:189:19)
at next (index.js:166:38)
at Layer.urlencodedParser [as handle] (index.js:70:44)

In the client
Cannot GET /insertUser means this is a GET route which is called by the browser when clicking on a link or entering the page URL.
But you specified app.post('/insertUser'... which means that the route will be called only when using the POST method (used when submitting forms for instance, NEVER when clicking on links)
If this is the result of a form, don't forget to specify the method (<form method="post">). Same for ajax calls.
If you want to test in dev mode you can use Postman on chrome to easily call POST routes. If you don't have chrome use curl.
Back-end
Express body parser isn't included in express 4.0 so you need to install it then use it:
var express = require('express');
var bodyParser = require('body-parser');
var schema = require("./schemas");
var app = express();
app.use(bodyParser());
app.get('/hello.txt', function(req, res){
res.send('Hello World2');
});
Then you can use req.body

I think in Express 4 you need to use router object instead of app to define the routes... Something like this:
var express = require('express');
var bodyParser = require('body-parser');
var schema = require("./schemas");
var app = express();
var router = express.Router();
router.get('/hello.txt', function(req, res){
res.send('Hello World2');
});
router.post('/insertUser', function(req, res){
console.log("Request handler 'insertUser' was called.");
});
...

Related

Problems POSTing json to Node/Express server from Axios/React

I'm current working on a web application using Node.js with Express in the back-end and React.js in the front end. In attempting to post user data to the Node server, through axios, I am running into an issue. When I make a post with the x-www-form-urlencoded content type, the front end will post to the server but the entire JSON of the posted data appears in the key field of the first element. When I change the content type to json it stops posting anything from the front end. I have tried cUrling to the server, and curling a JSON post will get accepted by the server.
React code to post to server
handleSubmit()
{
var form=this;
var axiosConfig = {
headers: {
'content-type': 'application/json; charset=utf-8'
}
}
axios.post('http://localhost:8080/api/login/', {
'username': form.state.username,
'password': form.state.password
}, {headers: {'content-type': 'application/json'}});
};
Server code for api endpoint
//From server.js
const express=require('express');
const session=require('express-session');
const bodyParser=require("body-parser");
const path = require('path');
var login = require('./routers/login')
var port = process.env.PORT || 8080;
var app=express();
app.use(session({'secret': 'thealphabetbackwardsiszyxwvutsrqponmlkjihgfedcba'}));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
//...
app.use('/api/login', login);
//from login.js
/* Router for login system
When user attempts to log in, check their credentials
If the user successfully logs in, create a session
If user enters invalid credentials prompt them
*/
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const user = require("./../models/UserSchema")
mongoose.connect('mongodb://localhost/newt');
const express = require('express');
const router = express.Router();
router.get('/', function (req, res)
{
console.log("Test");
})
router.post('/', function(req, res)
{
console.log(req.body);
res.end();
})
// To create test user use path localhost:8080/api/login/testing
router.get('/test', function (req, res)
{
var db = mongoose.connection;
var test = new user({
username: "joesephschomseph",
email: "testUser#test.com",
fname: "Joe",
lname: "Schmoe"
})
test.save();
console.log("Created test user!");
});
module.exports = router
npm install --save const body-parser
in app.js include const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
remove the single quotes from your 'username' and 'password'
console.log(req.body);

Both POST/GET requests yield a 404 error in Postman. Is my Express routing to blame?

I am intending to set up a Node.js server with MongoDB to handle HTTP CRUD requests. Upon setting up my endpoint I was initially able to receive POST/GET requests, however the handling of the document objects became the issue. Upon trying to fix this issue I am now unable to POST/GET at all? Is this simply a syntax issue or is my code doomed?
const MongoClient = require('mongodb').MongoClient;
var QRCode = require('qrcode');
var canvasu = require('canvas');
var express = require('express');
var mongoose = require('mongoose')
var app = express();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var db;
var collection
var Patient = require('./ShiftAssist/models/patientModel');
var router = express.Router();
''
CODE FOR CONNECTION
''
router.get('/patients/:Pnum', function(req,res,next){
Patient.findOne({Pnum:req.params.Pnum},function(err,patient){
if (err) return next(err);
res.json(patient);
})
});
app.use('/', router);
app.listen(3000, function () {
console.log('Example app listening on port ' + port + '!');
});
Expected: GET request to http://127.0.0.1:3000/patients/XXXXXX with a document identifier, returns entire document
Actual: Timeout Error
try to change you route by /patients/:Pnum
and your request should be http://127.0.0.1:3000/patients/XXXXXX
source: https://expressjs.com/en/guide/routing.html
EDIT: Code i used so far
var express = require('express');
var app = express();
var router = express.Router();
router.get('/patients/:Pnum', function (req, res, next) {
setTimeout(() => res.json({ ok: req.params.Pnum }), 1000)
});
app.use('/', router);
app.listen(3000);

Can not post to server using node express

I am trying to post data from postman to my node server, I keep getting 404.
Is my code setup correctly to receive post to http://localhost:8080/back-end/test and if not how can I fix it ?
var express = require('express');
var request = require('request');
var nodePardot = require('node-pardot');
var bodyParser = require('body-parser');
var rp = require('request-promise');
var app = express();
var port = process.env.PORT || 8080;
// Start the server
app.listen(port);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({extended: true})); // support encoded bodies
console.log('Test server started! At http://localhost:' + port); // Confirms server start
var firstFunction = function () {
return new Promise (function (resolve) {
setTimeout(function () {
app.post('back-end/test.js', function (req, res) {
console.log(req.body);
var login = req.body.LoginEmail;
res.send(login);
resolve({
data_login_email: login
});
});
}, 2000);
});
};
I am posting LoginEmail and keep getting 404.
Move app.post() outside of the timeout, promise, and firstFunction.
There is no proceeding paths defined in your code, so the path must start with a /: /back-end/test.js. Don't forget the extension since you've defined it.

ERROR app.use() requires middleware functions: (so how to set router for app.use in express node.js)?

basically im just trying to seprate routes, models, and controller in node.js application.
i have following files to setup very very basic node.js application.
controller/cv.js
module.exports = {
get: function(req, res, next){
console.log("GET REQUESTS")
next();
}
}
routes/cv.js
var express = require('express');
var CvRouter = express.Router();
var CvController = require('../controller/cv')
CvRouter.get('/', function(req, res, next){
console.log("GET REQUESTS")
next();
})
module.export = CvRouter
app.js
const express = require('express');
const bodyParser= require('body-parser')
var path = require('path')
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
var router = express.Router();
require('./router')(app)
app.listen(3000, function() {
console.log('listening on 3000')
})
router.js
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use([CvRouter]);
};
Basicaly this last file router.js is generting error when i use app.use([CvRouter])
ERROR is: throw new TypeError('app.use() requires middleware functions');
how i can resolve it? i also know its returning object of router. and app.use expecting function in parameter. but how i can achieve my desired MVC pattern of node.js?
as said in comment - you have a typo.
The file routes/cv.js contains module.export instead of module.exports, that makes CvRouter undefined.
Kill the array literal
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use(CvRouter);
};

req.body undefined on server side

I am working on app which uses node, express, mysql on server side. i have written serveral APIs on server.js file and when i am trying to access those using Postman then req.body is always undefined.
this is my server.js configuration.
var express = require('express');
var mysql = require('mysql');
var cors = require('cors');
var bodyParser = require('body-parser');
var wrench = require("wrench");
var fs = require('fs');
var path = require("path");
var mkdirp = require('mkdirp');
var walk = require('walk');
var fse = require('fs-extra');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var crypto = require('crypto');
app.use(cors());
app.use(bodyParser.urlencoded({limit: '50mb',extended: false}));
app.use(bodyParser.json({limit: '50mb'}));
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'dbname'
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
app.post('/urlreq', function(req, res){
console.log(req.body);
}
app.listen(3000, function(){
console.log("Rest Demo Listening on port 3000");
});
When i am trying send something in body in Postman then req.body is coming empty on server side.
If you are sending multipart/form-data, it doesn't work because bodyparser doesn't handle this body type.
In this case adding the following line should fix it:
app.use(multipartMiddleware);
Form the docs:
multipart/form-data is the default encoding a web form uses to transfer data
Try add:
var express = require('express');
var app = express();
[...]
// Last stack
app.listen(3000, function(){
console.log("Rest Demo Listening on port 3000");
});
You can use as a middleware also. Also listen on a port. add following lines in your code -
var app = express();
app.use(function(req, res, next) {
console.log('Current User:', req.body);
next();
});
app.post('/url', function(req,res){
console.log(req.body)
});
app.listen(3000, function(){
console.log('Express server listening on port 3000');
});

Resources