Node.js POST does not work - javascript

I am currently trying to learn how to use the MEAN stack and I'm having trouble with executing POST requests on the server.
This is my server.js script.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.get('/api/posts', function(req, res) {
res.json([
{
username: 'dickeyxxx',
body: 'node rocks!'
}
]);
});
app.post('api/posts', function(req, res) {
console.log('post received!');
console.log(req.body.username);
console.log(req.body.body);
res.send(201);
});
app.listen(3000, function() {
console.log("Server listening on", 3000);
});
I tried sending request to the server using curl. GET requests work without a hitch but POST requests are giving me much trouble. This is my curl statement:
curl -v -H "Content-Type: application/json" -XPOST --data "{\"username\":\"dickeyxxx\",\"body\":\"node rules!\"}" http://localhost:3000/api/posts
I'm getting HTTP 404 Not Found and CANNOT POST /api/posts
I've tried restarting my server.js script but to no avail.
How do I solve this problem? Thank you for your help.

You are missing forward slash at the beginning for POST. Try
app.post('/api/posts', function(req, res) {
res.send(201);
});

Related

syntaxerror unexpected token # in json at position 0 at object.parse (native)

I am testing a server.js file through curl from cmd for post request where I am getting the above error. I saw many related question and answers but nothing solves my problem.
Please provide me the solution.
This is my server.js
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.post('/data', function (req, res) {
console.log(req.body);
res.end();
});
app.listen(3000);
and This is curl code from cmd,
C:\Users\user\Downloads\Compressed\curl.exe -d '{"key1":"value1", "key2":"value2"}' -H "Content-Type: application/json" -X POST http://localhost:3000/data
This is the error I am getting,
error image. click here to see it.
You are using following body
'{\"key1\":\"value1\", \"key2\":\"value2\"}'
Use following instead
"{\"key1\":\"value1\", \"key2\":\"value2\"}"

Request body in express is undefined?

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.

How to setup express js server with firebase hosting?

I am trying to make an app using Instagram's real-time api. I want to use Firebase to host my server. Below is my folder structure:
-main.js (instagram get and post requests here)
-server.js (setup express server here)
-firebase.json
-public (all firebase files)
--index.html
--scripts
--styles
I first make my subscription to Instagram by typing this in my command line:
curl -F 'client_id=7be53c459291486ead4916048ac434ad' \
-F 'client_secret=88ad262f9e57481bbf1ea7312d179a50' \
-F 'object=tag' \
-F 'aspect=media' \
-F 'object_id=turtles' \
-F 'callback_url=https://instagram-slideshow.firebaseapp.com/callback' \
https://api.instagram.com/v1/subscriptions/
I get an invalid response when I make the subscription request. Where should I put my server code? In my public folder? I cannot find any examples on how to use firebase to host your server. Can someone show me an example?
This is my server.js code:
var express = require('express');
var app = express();
require('./app.js')(app);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
And this is my main.js
module.exports = function(app){
// when instagram tries to GET my URL, I need to return the hub.challenge and hub.verify_token
app.get('/callback', function (req, res) {
res.send('Hello World!');
if(req.param("hub.verify_token") == "myVerifyToken") {
res.send(req.param("hub.challenge"));
}
else {
res.status(500).json({err: "Verify token incorrect"});
}
});
// when instagram sends a post request to my server, check for updates on my end
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
}

How to receive data from an AJAX POST function at the server side with Node.js?

I am trying to send data to the server with the Ajax POST function, and then receive it at the server side with Node.js (and then manipulate it there) but the only problem is that I am unable to find any function at the Node.js side to allow me,accomplish this.I would really like it if you guys could help me out on how to do this as even related threads, I visited on many websites were not very helpful.
Thanks
It will be much easier for you to use some Node-framework like express, to handle all that routes and requests.
You can install it and body-parser module with these commands:
npm install express --save
npm install body-parser --save
Visit express API References to find out more: http://expressjs.com/4x/api.html
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
// Handle GET request to '/save'
app.get('/save', function(req, res, next){
res.send('Some page with the form.');
});
// Handle POST request to '/save'
app.post('/save', function(req, res, next) {
console.log(req.body);
res.json({'status' : 'ok'});
});
app.listen(3000);
Inside your app.post() route you can get access to any post data using req.body. So your S_POST["name"] will be req.body.name in this case.
here's a simple example:
var http = require('http');
http.createServer(function (request, response) {
switch(request.url){
case '/formhandler':
if(request.method == 'POST'){
request.on('data', function(chunk){
console.log('Received a chunk of data:');
console.log(chunk.tostring());
});
request.on('end', function(){
response.writeHead(200, "OK", {'Content-Type' : 'text/html'});
response.end()
});
}
break;
}
}
Also see this page.

How to access the request body when POSTing using Node.js and Express?

I have the following Node.js code:
var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());
app.post('/', function(request, response) {
response.write(request.body.user);
response.end();
});
Now if I POST something like:
curl -d user=Someone -H Accept:application/json --url http://localhost:5000
I get Someone as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body) but Node.js throws an exception saying "first argument must be a string or Buffer" then goes to an "infinite loop" with an exception that says "Can't set headers after they are sent."; this also true even if I did var reqBody = request.body; and then writing response.write(reqBody).
What's the issue here?
Also, can I just get the raw request without using express.bodyParser()?
Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:
app.use(express.json())
Like this:
const express = require('express')
app.use(express.json()) // <==== parse request body as JSON
app.listen(8080)
app.post('/test', (req, res) => {
res.json({requestBody: req.body}) // <==== req.body will be a parsed JSON object
})
Note - body-parser, on which this depends, is already included with express.
Also don't forget to send the header Content-Type: application/json
Express 4.0 and above:
$ npm install --save body-parser
And then in your node app:
const bodyParser = require('body-parser');
app.use(bodyParser);
Express 3.0 and below:
Try passing this in your cURL call:
--header "Content-Type: application/json"
and making sure your data is in JSON format:
{"user":"someone"}
Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:
var express = require('express');
var app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
console.dir(req.body);
res.send("test");
});
app.listen(3000);
This other question might also help: How to receive JSON in express node.js POST request?
If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681
As of Express 4, the following code appears to do the trick.
Note that you'll need to install body-parser using npm.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
For 2019, you don't need to install body-parser.
You can use:
var express = require('express');
var app = express();
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
You should not use body-parser it is deprecated. Try this instead
const express = require('express')
const app = express()
app.use(express.json()) //Notice express.json middleware
The app.use() function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.
Now to access the body just do the following
app.post('/', (req, res) => {
console.log(req.body)
})
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/post/data', function(req, res) {
console.log('receiving data...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
This will help you. I assume you are sending body in json.
This can be achieved without body-parser dependency as well, listen to request:data and request:end and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var express = require('express');
var app = express.createServer(express.logger());
app.post('/', function(request, response) {
// push the data to body
var body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
// on end of data, perform necessary action
body = Buffer.concat(body).toString();
response.write(request.body.user);
response.end();
});
});
In my case, I was missing to set the header:
"Content-Type: application/json"
Try this:
response.write(JSON.stringify(request.body));
That will take the object which bodyParser has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data and end listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.
The accepted answer only works for a body that is compatible with the JSON format. In general, the body can be accessed using
app.use(
Express.raw({
inflate: true,
limit: '50mb',
type: () => true, // this matches all content types
})
);
like posted here. The req.body has a Buffer type and can be converted into the desired format.
For example into a string via:
let body = req.body.toString()
Or into JSON via:
let body = req.body.toJSON();
If you're lazy enough to read chunks of post data.
you could simply paste below lines
to read json.
Below is for TypeScript similar can be done for JS as well.
app.ts
import bodyParser from "body-parser";
// support application/json type post data
this.app.use(bodyParser.json());
// support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
In one of your any controller which receives POST call use as shown below
userController.ts
public async POSTUser(_req: Request, _res: Response) {
try {
const onRecord = <UserModel>_req.body;
/* Your business logic */
_res.status(201).send("User Created");
}
else{
_res.status(500).send("Server error");
}
};
_req.body should be parsing you json data into your TS Model.
I'm absolutely new to JS and ES, but what seems to work for me is just this:
JSON.stringify(req.body)
Let me know if there's anything wrong with it!
Install Body Parser by below command
$ npm install --save body-parser
Configure Body Parser
const bodyParser = require('body-parser');
app.use(bodyParser);
app.use(bodyParser.json()); //Make sure u have added this line
app.use(bodyParser.urlencoded({ extended: false }));
What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.
The error you're getting doesn't appear to be related to any of the code you've shown us.
If you want to get the raw request, set handlers on request for the data and end events (and, of course, remove any invocations of express.bodyParser()). Note that the data events will occur in chunks, and that unless you set an encoding for the data event those chunks will be buffers, not strings.
You use the following code to log post data:
router.post("/users",function(req,res){
res.send(JSON.stringify(req.body, null, 4));
});

Categories

Resources