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.
Related
I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:
This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried. My current implementation goes like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()
//Import static files
app.use(express.static('../public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', jsonParser, (req, res) => {
console.log(req.body);
res.send(200);
});
app.listen(port, () => console.log("Server started"));
No matter what I try from other posts, it still does not seem to return me any data.
Does anyone have an idea how to fix this problem?
Why to you use 'jsonParser' in the app route? Try something like:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post-test', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});
im trying to get the params of my post request. I can send them with JSON and it will work (if i take out the type property of the BodyParser.json) but not form data. Im using the body-parser middleware as follows.
const BodyParser = require('body-parser')
const Config = require('../config/environment');
const Express = require("express");
const App = Express();
App.use(BodyParser.json({type: '/', limit: '50mb'}));
App.use(BodyParser.urlencoded({extended: false}));
App.listen(3000, () => {Response.logger('Api running on port 3000.');});
App.post("/signup", (req, res, next) =>
{
consoleAlert('SIGNUP', false);
console.log(req);
Account.signup(req.params).then(
function(results) {response(results, res, 'SIGNUP');},
function(error) {response(error, res, 'SIGNUP');});
});
So when i print out req, the body is always empty with form data
Written from scratch - this appears to work:
server:
//app.js
const express = require('express');
const bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.post('/', function(req, res, next) {
console.log(req.body);
});
app.listen(3022);
client: call curl from command line sending form data (application/x-www-form-urlencoded is the default), mine node server IP is 10.10.1.40 :
curl -d "param1=value1¶m2=value2" -X POST http://10.10.1.40:3022/
var https = require('https'),
fs = require('fs'),
express = require('express'),
app = express();
// cookieParser = require('cookie-parser'),
// path = require('path'),
// bodyParser = require('body-parser'),
// https = require('http');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync('encryption/massif_wildcard.crt');
var ca = fs.readFileSync('encryption/DigiCertCA.crt');
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
app.get('/', function (req, res) {
res.header('Content-type', 'text/html');
return res.end('Hello World!');
});
// app.set('view', __dirname + '/views');
// app.use(bodyParser.urlencoded({
// extended: true
// }));
// app.use(bodyParser.json({
// limit: '500mb'
// }));
// app.use('/', express.static(path.join(__dirname, '/dist/basic-structure')));
// app.get('/**', function (req, res, next) {
// console.log(req, res, next);
// res.sendFile('index.html', {
// root: __dirname + '/dist/basic-structure'
// });
// });
console.log("listening to port 8000");
Here i have written hello world just to test my code.so in this case code runs but its not secure. I want my connection to be secure.In this case it shows deprecated http and shows certificate error.but and run unsecurly.
Again if I replace the hello world part with the commented part as shown in my code it doesn't even run with the deprecated http.if i replace the https with http it runs. I want help in running my edited code. If i am missing some points please let me know.
In short this code is running insecurly , i want to make it secure
Not sure if I understand well, but if by "the code is not running" you mean your app, then it seems your 2nd code set simply try to run a server but not your app
To my understanding, you are defining your app as express but you are not using it, so it will not be delivered
So my guess is that you will need to use the https server command with the app and its options to link everything together (https and app) as suggested by #lx1412
I would try this :
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
// https = require('http'),
https = require('https'),
app = express(),
fs = require('fs');
var key = fs.readFileSync('encryption/star_massifsolutions_com.key');
var cert = fs.readFileSync( 'encryption/massif_wildcard.crt' );
var ca = fs.readFileSync( 'encryption/DigiCertCA.crt' );
var httpsOptions = {
key: key,
cert: cert,
ca: ca
};
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
// https.createServer(httpsOptions, (req, res) => {
// console.log("code works");
// res.writeHead(200);
// res.end('hello world\n');
// }).listen(8000);
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("code works");
res.writeHead(200);
res.end('hello world\n');
});
EDIT :
Can you simply try this and see how it behaves ?
Also, can you provide your deprecated http and certificate error ?
app.get('/', function (req, res) {
res.send('Hello World!');
});
https.createServer(httpsOptions, app).listen(8000, function () {
console.log("server running at https://IP_ADDRESS:8000/")
});
It's simple.
var express = require('express'),
cookieParser = require('cookie-parser'),
path = require('path'),
bodyParser = require('body-parser'),
http = require('http'),
app = express();
app.set('view',__dirname+'/views');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json({limit: '500mb'}));
app.use('/', express.static(path.join(__dirname,'/dist/basic-structure')));
app.get('/**', function(req, res, next) {
console.log(req, res, next);
res.sendFile('index.html', { root: __dirname +
'/dist/basic-structure' });
});
//Start Server
//app.listen(3004, function(){
// console.log('>>>3004')
//});
//complete your code here
https.createServer(httpsOptions,app).listen(8000);
I have issue setting up routes for user in below code, I want to use express middleware and trying routes using app.use.
index.js is invoking user controller method once api's is being called So in below code i am trying to post data api/users from client but it returns 404.
How can i fix this issue using below routes setup ?
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
var db = require('./config/db');
var port = process.env.PORT || 8080;
mongoose.connect(db.url);
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app); // configure our routes
require('./config/express')(app);
app.listen(port);
console.log('listening on port ' + port);
exports = module.exports = app;
app > routes.js
module.exports = function(app) {
app.use('api/users', require('./api/user'));
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
// res.sendFile(path.join(__dirname, ''../public/views/index.html''));
});
};
config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
// import cookieParser from 'cookie-parser';
// import errorHandler from 'errorhandler';
var path = require('path');
// import lusca from 'lusca';
var config = require('./db');
var mongoose = require('mongoose');
//var mongoStore = connectMongo(session);
module.exports = function(app) {
// app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
}
User index where i will handle all crud operation for user
app > api > user > index.js
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
router.get('/', controller.index);
router.post('/',controller.create);
module.exports = router;
1st:
To handle all request
Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
app.use(function(req,res)
{
res.sendfile('./public/views/index.html');
console.log("Not found....I will handle *unhandle* rout here for you");
})
// app.get('*', function(req, res) use the above function instead of this
But this function at the end so it will only excute when no route path found to the app object.
Express documentation
2nd:
To handle createuser
var express = require('express');
var controller = require('./user.controller');
var router = express.Router();
// you must define route which you want to handle in user file
router.get('/api/user', controller.index);
router.post('/',controller.create);
module.exports = router;
Update working example with some explanation
Your app.js file
var express=require('express')
var app=express()
app.use('api/user',require('./user'))
app.use('/',require('./user'))
app.use(function(req,res)
{
res.sendfile('stack10.html')
console.log("Not found....I will handle *unhandle* rout here for you");
})
app.listen(8080,function()
{
console.log("server listening on port 8080")
})
user.js
var express = require('express')
var router = express.Router()
var app=express()
router.get('/api/user', function(req, res) {
res.send('respond for ..../api/user')
});
router.get('/',function (req,res) {
res.send('respose for ..../')
})
module.exports = router;
Your app.use will be app.use(api/user) while in user will be router.get(/api/user) so when u try http://127.0.0.1:8080/api/user
your response will be respond for ..../api/user
app.js:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var person = require('./routes/person');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/person', person);
module.exports = app;
routes/person.js:
var express = require('express');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var router = express.Router();
/* GET page. */
router.get('/', function (req, res) {
res.render('person', {
message: 'Person works'
});
});
router.post('/', urlencodedParser, function (req, res) {
res.send('Thank you!');
console.log(req.body.firstname);
console.log(req.body.lastname);
});
views/person.pug:
extends layout
block content
h1 Welcome #{id}
p= message
br
h2= qstr
br
form(method='post', action='/person')
label First name
input#firstname(type='text')
br
label Last name
input#lastname(type='text')
input(type='submit', value='Submit')
Questions:
1) Is it necessary in every route to add?:
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
2) Why do I get this:
1.You don't need to use body-parser in every route. Body-parser is a middleware which is used to obtain data from application/x-www-urlencoded content type. So if you're sure sure that data you will get in your body is not x-www-urlencoded type, you don't need to use it.
2.Please check if you are passing the data in post request. You can use chrome extension postman to form any kind of query.