cannot get POST request on express - node.js

I can't get any POST requests with the express framework.
This is my code
var express = require("express");
var app = express();
app.set("view engine","ejs")
app.get("/", function(req, res){
res.render("home");
});
app.post("/addfriend", function(req, res){
res.send("you have reached the post route succesfully");
});
app.get("/friends", function(req, res){
var friends =["lara","tommy","miranda","faith","locas"];
res.render("friends",{friends : friends});
});
app.listen(3000, function(){
console.log("server is listening on port 3000");
});
any suggestion please.

Few observations.
1)You are missing body parser for your app.js ( if in future you want to read form data).
just add this to your app,js
const app = express();
app.use(bodyParser.json());
Wherever you are using trying to send post request for example a HTML form or a button does it have correct route, it should match with this post route /addfriend.
Browser always send get request to server from browser, to specifically send post request use postman, curl or a HTML form.
If you are using postman try this https://learning.postman.com/docs/sending-requests/requests/#sending-body-data
For the difference between get and post follow this
Edit :-
Http post request means :- "The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header."
get request :- "The HTTP GET method requests a representation of the specified resource. Requests using GET should only be used to request data (they shouldn't include data)."

Related

Post Method does not get to the end point while using Express/Node.js

It is a simple code for sending a post request to a server but when I hit the end point it shows [Cannot get / "endpoint"]. However, when I send a get request, server responds with message "Ok". Please help me out here that what I am missing.
import express from 'express'
import bodyParser from 'body-parser'
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});
app.listen(8080, () => console.log(`Started server at http://localhost:8080!`));`
Below is my Packago.json file.
The message I receive while hitting the endpoint is shown below
.
When we open a URL on a browser, that is a GET request and we want to read data. As far as POST request is concerned we have to use an API platform such as Postman to make a POST request as we submit our data to the server. That's it.

Postman send strange response for raw JSON post (node js)

I'm trying to do a POST request using raw json.
In the Body tab I have "raw" selected with this body:
{
"name": "book"
}
On the Node js side I'm doing res.send(JSON.stringify(req.body))
router.post('/', (req, res, next) => {
res.send(JSON.stringify(req.body));
}
And in POSTMAN response I receive:
{"{\n\"name\": \"book\"\n}":""}
When expected something like
{"name":"book"}
Have no idea - where could be a reason for it?
You'll need to use the Express JSON body parser, install using
npm install body-parser;
Then:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Once you do this, the JSON data will be parsed correctly and when you send it back it will render correctly.
Also make sure you have your Content-Type header set to "application/json" in your Postman request (go to "Headers" and add a new "Content-Type" header with value "application/json")
Here's a simple express app that will echo any JSON POST:
const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post('/', (req, res, next) => {
console.log("Body: ", req.body);
res.send(JSON.stringify(req.body));
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
If you're on Express v4.16.0 onwards, try to add this line before app.listen():
app.use(express.json());
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Looks to me like its not a fault of Postman, but your NodeJS service is applying JSON.stringify twice?
Can you log the response type from the server to console to check whether its already json content or not?
try with hard coded json response and then with dynamic variable
res.json({"name":"book"});

Forward request object(POST) from express js server to another express js server

I want to forward a post request from an express server(from inside post method) to another express server's post method.
Is there any way to do that?
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer();
var lb = 'http://localhost:8000';
after that inside post,
app.post('/emaillist', function(req, res){
console.log(req.body); // printing params correctly
console.log('redirecting to loadbalancer');
console.log(req.body);
apiProxy.web(req, res, {target: lb});
Here problem is that I can't retrieve request paramaters/body sent, in loadBalancer server. When trying to retrieve a property(e.g. email) out of request loadBalancer,
console.log(req.body.sender);
It says cant read a property of undefined.
My question is how to send request to another noder server from a node server and how to retrieve request parameters out of it at receiving node server

A simple http GET request doesn't hit the express js api

I have a simple node/express js api that receives request from another app.The request is this GET /api/users?data=5. Whenever i hardcode data with 5 like above, it does hit /api/users route.But whenever i send the request with dynamic data like GET /api/users?data=id where id = 5, it DOESN'T hit /api/users route, But in the server logs i do see the request did hit with url /users?data=5.I am not sure whats wrong but i am suspecting maybe i didnt define the routes correctly.Any help will be appreciated.Sorry I am new to Node js. Thank you.Here is my code
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
next();
});
router.get('/', function(req, res) {
res.render('home');
});
app.use('/api', router);
router.route('/users')
.get (function(req, res) {
var data = req.query.data;
});
I figured it out , in the request GET /api/users?data=id HTTP/1. id was not properly formated ,hence the request was hitting the server but not application layer.
UPDATE
In short the app that make Http GET request is written in arduino (which translates it to C).I was reading the ID from the device memory which is saved as char array.So i thought i had converted the char array to string but in reality was still chars, and i put this variable in the url for Get request that is why it was complaining.

Cross-domain POST request in Node.JS with preflight?

I have just started with Node.
I am trying to get cross-domain form data from an HTML form to parse in a Node.js server. I have been able to do this with simple POST data, not with POST requests that require preflight.
I am running the Node code on cloud9 app servers. I am also using the Cors module to handle the requests. This module works well with simple requests (test here to see a simple request work), however with requests that require preflight I get this result from the Chrome inspector console.
XMLHttpRequest cannot load https://nms-motaheri-1.c9.io:8080/mail.
The request was redirected to 'https://c9.io:8080/api/nc/auth?.....SHORTENED',
which is disallowed for cross-origin requests that require preflight.
Here is my server.js code:
// Define dependencies
var express = require('express')
, cors = require('cors')
, app = express()
, parse_post = require("parse-post");
// Core module config
var corsOptions = {
origin: '*',
preflightContinue: true // <- I am assuming this is correct
};
app.use(cors(corsOptions));
// Respond to option request with HTTP 200
// ?? Why is this not answering my OPTION requests sufficiently ??
app.options('*',function(req,res){
res.send(200);
});
// Give a hello world response to all GET requests
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
// Handle all POST requests to /mail
app.post('/mail', parse_post(function(req, res) {
console.log(req.body);
res.json({msg: 'This is CORS-enabled for all origins!'});
})
);
// Listen on default Cloud9 port which is 8080 in this case
app.listen(process.env.PORT, function(){
console.log('CORS-enabled web server listening on port ' + process.env.PORT);
});
Why is this happening and how can I satisfactorily answer the OPTION request for my POST with pre-flight?
Here is the post request and response in Chrome dev tools:
Turns out that part of the problem was that the cloud9 server was set to private making these requests all redirect.
After making the server public, the redirections stopped. However, I received an error that the Node.js server did not have any Access-Control-Allow-Origin headers to allow requests from my cross origin domain. I noticed that "simple" with-out preflight requests would go through. So instead of trying to understand why it was not accepting my allow-all-origin-configuration on the Node.js side I decided to serialized the POST data to get rid of the preflight requirement and changed the data type in my angular request to plain text.
To get rid of preflight, first get rid of any POST header configuration (cache, etc), make sure your request Content-Type is plain text and make sure your actual content is plain text too. So if it is in JSON serialize it in jQuery before sending it with POST.
This is what my new Angular Post request code looked like:
sendEmail: function(email) {
var config = {
headers: {
'Content-Type': 'text/plain'
}
};
var POSTDATA= JSON.stringify(POSTDATAJSON);
return $http.post(POSTURL, POSTDATA, config)
}
And in Node.js this, I am using the cors Node.js module:
app.post('/mail', parse_post(function(req, res) {
var postReq = JSON.parse(Object.keys(req.body));
}));

Resources