curl with nodejs express - POST data - node.js

I'm trying to simulate a POST request to a server app based in Express for nodeJS. It's running on localhost:3000 (JS Fiddle: http://jsfiddle.net/63SC7/)
I use the following CURL line:
curl -X POST -d "{\"name\": \"Jack\", \"text\": \"HULLO\"}" -H "Content-Type: application/json" http://localhost:3000/api
but get the error message:
Cannot read property 'text' of undefined
Any ideas what I'm doing wrong?
Note: I can make a successful GET request using this line:
curl http://localhost:3000/api

Assuming you're trying req.body.text,
Have you used bodyParser?
app.use(express.bodyParser());

The answer by josh3736 is outdated. Express no longer ships with the body-parser middleware. To use it you must install it first:
npm install --save body-parser
Then require and use:
let bodyParser = require('body-parser');
app.use(bodyParser());

Just to update Thordarson's answer (which is now deprecated), the currently recommended way is:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
See also https://stackoverflow.com/a/24330353/3810493

Related

Erroneous newline only when executing a curl request with nodejs app

I have a simple Nodejs server using express.
// App.js
const express = require("express");
const app = express();
app.get("/", (req, res, next) => {
res.status(200).send("Foo");
});
app.listen(3001);
When I am visiting localhost3001 in Chrome I see the anticipated output.
When I execute curl --request GET --write-out "%{http_code}\n" http://localhost:3001/ I get...
curl --request GET --write-out "%{http_code}\n" http://localhost:3001/
Foo200
When I was anticipating...
curl --request GET --write-out "%{http_code}\n" http://localhost:3001/ Foo200
I sent the output to a text file and observed no newline. Is there anyway to supress this newline?

I'm stuck on this Error from Udemy course on NodeJS and express by Jonas Schmidtmann

I have tried multiple solutions on here, but nothing seems to work, can anybody help me ??
GET https://api.mapbox.com/mapbox-gl-js/v2.9.1/mapbox-gl.js net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200
By the looks of this error, try install cors as a dependency. Now if you're using express try this code
const cors = require('cors');
app.use(cors({
origin: '*'
}));

Sever returning 400 when body passed with GET

I have an Express GET route to fetch all users. Whenever a req.body is present, the server is always responding with 400.
Obviously, I have body-parser and this behaviour is only experienced in the production k8s environment (working fine in localhost)
Is there any limitation to send req.body to GET routes? Express documentation doesn't say so
You need to set the content type --header "Content-Type: application/json" in the GET request and it should work.
curl --header "Content-Type: application/json" --request GET --data '{"username":"xyz","password":"xyz"}' https://example.com/posttest
and here is the nodejs snippet
app.get('/posttest', function(req, res){
console.log("posttest call received")
res.send(req.body);
});

restify 2.6.1 how to disable body parser for specific request

I am pretty new to node.js services and I am facing a problem with multipart/form-data content type. I need a way to disable body parser functionality for specific request.
I am using restify 2.6.1.
Below are some snippet of the configuration.
My setup is:
App.js :
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.jsonp());
server.use(restify.bodyParser());
server.use(restifyValidator);
server.use(restify.gzipResponse());
server.use(passport.initialize());
server.use(restify.conditionalRequest());
Route.js :
app.post({path: '/test/upload/:upload_image_name', version: ver}, uploadCtr.uploadImage);
app.post( {path: '/test/upload/:upload_image_name', version:ver }, passport.authenticate('bearer',{ session: false}),uploadCtr.uploadImage);
Without restify.bodyParser() the upload image is working( but everything which is relying on the json parser is failing )
Thanks in advance.
You shouldn't use bodyParser() for every route by default. In fact, you should only use bodyParser() for routes that require multipart uploads.
All servers using express.bodyParser are vulnerable to an attack which creates an unlimited number of temp files on the server, potentially filling up all the disk space, which is likely to cause the server to hang.
Demonstration
This problem is extremely easy to demonstrate. Here's a simple express app:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/test', function(req, resp) {
resp.send('ok');
});
app.listen(9001);
Seems pretty innocuous right?
Now check how many temp files you have with something like this:
$ ls /tmp | wc -l
33
Next simulate uploading a multipart form:
$ curl -X POST -F foo=#tmp/somefile.c http://localhost:9001/test
ok
Go back and check our temp file count:
$ ls /tmp | wc -l
34
That's a problem.
http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
This problem also exists with Restify.
You can solve the problem by replacing .bodyParser() with:
server.use( restify.queryParser() );
server.use( restify.jsonBodyParser() );
But to answer your question about a particular route, you should move any middleware that you don't need for all routes into route specific middleware:
server.get('/route', restify.queryParser(), restify.jsonBodyParser(), routeHandler);
This can also take an array:
var routeMiddleware = [
restify.queryParser(),
restify.jsonBodyParser()
];
server.get('/route', routeMiddleware, routeHandler);

Add session support to express after setup

I am just starting to figure out nodejs and I forgot to put in the flag for session support
$ express -s somefolder
Can I run the above command without overwriting anything I already added or changed or do I have to do something else?
it is not as clear as adding a new dependancy (stylus) to package.json and rerun $ npm install
Update:
Session support is now added via the expressjs/session module.
To install:
npm install -save express-session
To use:
import * as session from "express-session";
...
app.use(cookieParser());
app.use(session({ secret: "..." });
Be sure to visit the module on GitHub to get the latest installation and usage instructions.
Original answer:
Just add the session middleware to your Express app.js file.
app.use(express.cookieParser());
app.use(express.session({secret: '1234567890QWERTY'}));
Make sure it comes after the express.cookieParser() call. Also, update the secret value to a random string for security.

Resources