I have the following code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/rasp', function(req, res) {
res.send("received");
res.send(req.body.data);
});
app.listen(process.env.PORT || 5000);
I used POSTMAN to see if it worked and apparently the "received" text is sent back, but the data parameter is blank. What could be the problem?
Basically, the client sends a request and waits for a single response from your server. Once the client receives that response, it stops waiting for another. Furthermore, Express only allows you to send one response per request (going along with the client stuff explained above). You may be able to change this setting, but I've never dealt with it, so my answer will be limited to that knowledge.
Your server is executing res.send('received'); and the response is handled. You cannot call res.send again. You should be getting an error on your server when you attempt the second call.
You should send all data that the client needs in the first (and only) res.send().
Server responses should not be handled like logging (ex: sending 'received', 'analyzing', etc). Keep the logging separate. The client doesn't want to know all that extra info, it just wants the expected data response.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(process.env.PORT || 5000);
app.post('/rasp', function(req, res) {
res.send({received:true,data:req.body});
});
can you try this one and writing the response here
I believe your post body is "data=Some Value".
If you want to send multiple chunks of data, you should use res.write, and res.end. In your code change the following lines
res.send("received");
res.send(req.body.data);
to
res.write("received");
res.end(req.body.data);
Related
I'm trying to setup a NodeJS express JSON REST API for the first time, but I'm facing some troubles while trying to retrieve the JSON data coming from the requests (both GET and POST requests)
Here's the code:
var bodyParser = require("body-parser");
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/prova", (req, res)=>{
console.log(req.headers["content-type"]);
console.log(req.body);
res.status(200).json(req.body);
});
Here's the console.log();
When trying to make a request with Postman with some parameters:
application/json
{}
And here are the Postman request's details
You should avoid sending body with HTTP GET methods as per MDN web docs. As for the shown GET method this line res.status(200).json(req.body); is giving you an empty object, change it for example to res.status(200).json({message:"Hello world!"}); to see the message. For the POST method you can access the body as you do with req.body.
Here's my app.js file.
var express = require('express'),
bodyParser = require('body-parser'),
oauthServer = require('oauth2-server'),
oauth_model = require('./app_modules/oauth_model')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
var jsonParser = bodyParser.json();
app.oauth = oauthServer({
model: oauth_model, // See below for specification
grants: ['password', 'refresh_token'],
debug: process.env.OAUTH_DEBUG,
accessTokenLifetime: 172800,
refreshTokenLifetime: 172800,
authCodeLifetime: 120,
});
// Oauth endpoint.
app.all('/oauth/token', app.oauth.grant());
// User registration endpoint.
app.post('/users', jsonParser, require('./routes/register.js'));
// Get user details.
app.get('/users', app.oauth.authorise(), require('./routes/users.js'));
app.post('/', app.oauth.authorise(), require('./routes/test.js'));
app.use(app.oauth.errorHandler());
app.listen(3000, function () {
console.log('Mixtra app listening on port 3000!')
})
When I send an invalid json body with POST request to localhost:3000/users the request goes to register.js and the validation code works there.
but strangely when I send valid JSON body, it says "Cannot POST /users" with a 404 Not Found HTTP status code and nothing in terminal log.
Note: I'm using postman to send the api requests.
It would be really great if someone could help me with this.
Thanks,
Joy
I don't see you using the jsonParser
You should use it before sending any json to it
app.use(jsonParser);
I am making a simple POST request using Alamofire (in iOS) and handling it in node using express.
My code in iOS:
let boop: [String: AnyObject] = ["username":"fakeuser"];
Alamofire.request(.POST,"http://localhost:3000/test", parameters: boop, encoding: .JSON)
And this is my code in node:
var app = require('express')();
var http = require('http').Server(app);
app.post('/test', function(req, res){
console.log("THE SERVER HAS RECEIVED THE POST! \n")
console.log(req.body);
});
http.listen(PORT, function(){
console.log('listening on *:3000');
});
My terminal console prints out "the server has received the post" , so I know that the post is actually triggered. The issue is that instead of logging the req.body, it instead prints out "undefined". I've looked around and it seems like a "body parser" thing needs to be configured but apparently that is obsolete with the new version of express. So I am lost as to what to do.
Any advice?
I'm pretty sure you need to add the body-parser to your express app to parse the JSON.
const bodyParser = require('body-parser');
app.use(bodyParser.json());
See http://expressjs.com/de/api.html#req.body.
I am testing the post method to create a todo item as follows. I am using postman in chrome to simulate the post method call. However, it does not work and gives me the below error. I suspect something is wrong with the way body-parser library is working. What am I doing wrong here?
1 SyntaxError: Unexpected token b
2: at parse (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/types/json.js:83:15)
3: at /Users/zack/mydrive/proj/express-demo/node_modules/body-parser/lib/read.js:116:18
4: at invokeCallback (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:262:16)
5: at done (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:251:7)
6: at IncomingMessage.onEnd (/Users/zack/mydrive/proj/express-demo/node_modules/body-parser/node_modules/raw-body/index.js:308:7)
7 at IncomingMessage.emit (events.js:104:17)
8 at _stream_readable.js:908:16
Code:
var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var bodyParser = require('body-parser');
//MIDDLEWARE
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}));
// TODOS
var todos = [
{ body: "take out the trash",completed: false},
{ body: "Do the laundry",completed:true},
{ body: "Make a screencast",completed:false}
]
app.post('/todos', function (req, res){
console.log("todo:", req.body);
var todo = req.body;
console.log("todo:"+todo);
todos.push(todo);
res.status(200).json(todo);
res.send('OK')
})
Further I observe that the problem is because of this line.
app.use(bodyParser.json());
Are you sure you are sending the request as JSON? Make sure you've selected it in Postman - https://imgur.com/j0M7TEX.
If that didn't work, you can try the following -
...
app.post('/todos', function (req, res){
console.log("todo:", req.body);
var todo = req.body;
console.log("todo:"+todo);
todos.push(todo);
// Only try to send a single response.
res.json(todo);
});
It looks like you were trying to send two responses, one containing JSON, and another with text/plain ('Ok').
http://expressjs.com/fr/api.html#res.json
It seems like your program is trying to interpret the post data as json data - and generating an error when it trys to parse the request data which is probably url-encoded.
Perhaps consider sending your data in json format. You will have to set the request headers to indicate the datatype is json. See this answer for an example:
Angular JS POST request not sending JSON data
I just created a new session in postman and it started working. I am not sure if there is a caching effect but it works now. I did not make any code change at all. Posting this as the solution now.
Just don't put quotes on your JSON value.
Not "okay2" but just okay2.
I think that postman adds the quotes himself if needed and in this case creates ""okay2"" which isn't valid JSON.
By the way you can test by clicking on the "row" radio button and write your own JSON.
I am building a webservice, for which i am using nodejs, phantomjs and expressjs. I am learning all the three.
I want to serve a delayed response to the clients after processing their query. Like for example,
I am processing certain inputs from my client, then, i want to process the data at the backend which will take approx 10 sec on an avg. Then i wanted to serve this page to the client.
Is it possible in node to send multiple responses to the same request or delayed responses so that the template will automatically update the contents.
Or , should i use the same method , like store the json in a file in the server , then serve the page with ajax which will query the page.
please help me. here is the code which i wrote ,
app-server.js(the main file):
// import express module
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// define all required template files to be served and also define the template engine
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
// Useful modules
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// import the routes
require('./router')(app);
app.listen(8080);
router.js:
var crypto = require('crypto');
var express = require('express');
module.exports = function (app) {
// define the static routes.
app.use('/static', express.static('./static'));
app.use('/media', express.static('./media'));
//defining the controller.
var parserlib = require('./controller.js')
// Define the home root path
app.get('/', function (req, res) {
// shows the home search page.
res.render('index', {content:'template success'});
});
app.get('/search', function(req, res){
res.redirect('/');
});
app.post('/search', parserlib.parserlib);
}
controller.js:
var crypto = require('crypto');
var path = require('path')
var childProcess = require('child_process')
exports.parserlib= function(req, res){
var output = '';
var url = req.body.search_url;
var childArgs = [
path.join(__dirname, 'external-script.js'),
url,
]
// execute the script in a separate thread.
childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
// handle results
console.log(stdout);
output = stdout;
//console.log(err);
//res.send(output);
});
//res.send(output);
};
so , what i want to see is, first send a response to client stating that its loading, then i want to update the with processed data. In other languages its not possible to send multiple responses. Not sure about nodejs.
Also, do i have to store the json output from the processed lib to a file and then use ajax to query ? or is it possible to directly update the json object to the client ?
Thanks
This is just not how HTTP works. The clients won't expect it. This has nothing to do with Node or any other framework. The way to do what you're attempting is to actually send a response that the thing is loading, and then have some other mechanism for reporting state.
As an example, you might design a RESTful API. In that RESTful API you might define a endpoint for creating new things:
POST /api/things
The client would post data to that to create a new thing. The response should be something that provides a location of the newly created resource, for example an HTTP 301 to /api/things/1.
If the user goes to /api/things/1 and the thing isn't done getting made yet, then you can either do a temporary redirect (303) to /api/things/1/status which provides some helpful status information, or just issue a 404.
If you actually want to send back server-side pushes of status information, then you should be looking at WebSockets or a pure Socket API of some kind, neither of which is provided by Express, but both of which are available in Node (checkout the socket.io library and the net core library)