Where is POST method saved in express? - node.js

So I'm new to Backend and is learning about HTTP request. As far as I know GET is for getting a resource from backend and displays it on the browser. Then there is POST to post a resource, but where does it posted? I'm using express as framework. This is my code:
let bodyParser = require('body-parser');
let express = require('express');
let app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.post('/name', (req, res) => {
let first = req.body.first;
let last = req.body.last;
res.json({
'name': `${first} ${last}`
})
})
module.exports = app;
I successfully displayed the respond (a JSON with properties name: ${first} ${last}) after I submitted the form. But where does this JSON is saved? How can I access the JSON again?
Do I still need to push it to database to have access to submitted JSON? Because I thought before, POST will POST the submitted value.
Any helpful answer would be appreciated.

res.json is similar to sending response data back to the client side. At the client side, you can use a variable to store the result of calling this http request and then you can use the data it sends back.

Related

cannot get POST request on express

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)."

JSON comes in undefined, where is the data lost?

I am using postman to test a rest API I'm building for a project. I'm trying to send some data to a post method, but the data is getting lost somewhere between Postman and the endpoint.
I've tried tracing the data with console logs, but nothing comes out (req.body is undefined). I'm pretty sure the issue isn't with the endpoint or router, as the same error comes up in postman as in the console of my IDE, which means there's some sort of communication.
// json I'm putting into postman. validated with Jsonlint.com
{
"Name": "testN",
"file": "file1",
"Path": "/home/userf",
"userName": "user1"
}
// profileWrite.js
const dbProfileWrite = require('../...db-ProfileWrite');
const bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
// my post method
async function post(req, res, next) {
try {
console.log("attempting to parse data: " + req.body);
let profile = req.body;
console.log("data parsed, writing profiles");
profile= await dbProfileWrite.writeProfile(profile);
res.status(201).json(profile);
} catch (err) {
next(err);
}
}
module.exports.post = post;
UPDATE 7/15/19:I have recreated a microversion of my project that is having this issue on stackblitz. there's some sort of package error that I'm working on, but here's the link. I've recreated the methodology I'm using in my project with the router and all and looked at the example in the express docs. hopefully this helps isolate the issue.The data still comes in undefined when I post to this api through postman, so helpfully this much smaller view of the whole project helps.
Assuming you are using Express framework, by the look of the post function. You need to use a middlewear function to process request body using body-parser. Make sure you are using the correct parser in this case
app.use(bodyParser.json())
You don't need body-parser anymore it was put back in to the core of express in the form of express.json, simply use app.use(express.json()).
To access the body of your request use req.body, it should come with a object with the keys representing the json sent;
var app = express();
app.use(express.json());
async function post(req, res, next) {
try {
console.log("attempting to parse data: " + req.body);
let profile = req.body; // no need to use any functions to parse it
console.log("data parsed, writing profiles");
profile= await dbProfileWrite.writeProfile(profile);
res.status(201).json(profile);
console.log("profilecreated");
} catch (err) {
next(err);
}
}
See the express documentation
Solved the issue myself with a little help from John Schmitz. The issue was that I was defining the router and the server before actually telling it how to handle json bodies/ objects, so the body came through as the default undefined. In my index.js, the following is what fixed the code:
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/api/v1', router);
the key to this is that the app is told to use json and express.urlencoded before the router is declared. these actions have to happen in this order, and all before app.listen is called. once the app is listening, all of its params are set and you can't change them. Tl;dr: node is VERY picky, and you HAVE to define these things in the right place. thanks all for the help.

POST from Slack for button interactions has empty body

I'm setting up a Slack bot using node.js. The event system works perfectly and gives me POSTs with valid bodies from Slack, and I am able to successfully send messages (both interactive and not) to Slack.
However, the POSTs Slack sends me in response to an interaction with the buttons on interactive messages has an empty body. Interestingly, the Slack headers are still well-formed, although it fails to pass the signing secret test (which I know I implemented properly since event POSTs from Slack pass it).
I've set up everything for interactions according to Slack's own documentation here: https://api.slack.com/messaging/interactivity/enabling. I'm using express, request, and XMLHttpRequest to receive and send HTTP methods. If anyone has encountered this problem or has any insights, that would be great. Thanks!
Here's a code snippet for my function receiving POSTs from interactions:
var express = require('express');
var request = require('request');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/interaction', (req, res) => {
res.sendStatus(200);
var payload = {
"channel": req.body.payload.channel, // Breaks here since req.body is empty
"text": "Selected choice " + req.body.payload.actions.text.text
}
var r = new XMLHttpRequest();
r.onload = () => { var status = request.status; var data = request.responseText; }
r.open("POST", request_url, true);
r.setRequestHeader("Content-Type", "application/json");
r.setRequestHeader("Authorization", "Bearer " + botToken);
r.send(JSON.stringify(payload));
});
The Slack documentation doesn't seem to mention this, but empirically it would seem that the content type for webhook calls to apps uses Content-Type: application/x-www-form-urlencoded. You'll want to add:
app.use(bodyParser.urlencoded({ extended: true }));
In addition, the payload parameter can't be accessed as you're doing: it's actually a JSON object serialized as a string. This is documented here: https://api.slack.com/messaging/interactivity/enabling#understanding_payloads
The request will be made to your specified request URL in an HTTP POST. The body of that request will contain a payload parameter. Your app should parse this payload parameter as JSON.
So your code will want to do something like this:
var slack_payload = JSON.parse(req.body.payload);
var payload = {
"channel": slack_payload.channel,
"text": "Selected choice " + slack_payload.actions.text.text
}

How can I replace a collection with PUT using express?

I'm trying to take a json collection of data and send it with postman or Advanced REST Client. The biggest thing I'm getting stuck with with is where the data is. I can't seem to find it in any part of the request. Note this must be done using express.
app.put('/api/', function (req, res) {
//Get data and replace table in database
res.send("RECEIVED");
});
You can use body-parser to parse the request and provide you all that submited data through request.body.data if you send you data as a form-data or request.params.data if you send your data as a query parameter.
npm install body-parser --save
And import it and use it as a middleware
var bodyParser = require("body-parser");
// some other code goes here like
// var express = require("express"):
// var app = express()
// and here attach the body-parser middleware like thiss
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
when you make a request with any Advanced REST client each key in the JSON that you pass to the request body will be accessible as request.body.key you can learn more about body-parser body-parser doc

ajax call cant pass parameter to nodejs app

I make a ajax call via code below and expect to see parameters passed nodejs app, but it always empty
#action postData() {
$.ajax({
url:"http://localhost:8080/sendMail",
ContentType:'application/json',
dataType:'json',
type:'post',
data:JSON.stringify({'message':'helloworld'}),
success:(result) =>{
..
})
If I make a post request within postman(adding raw string json parameters to body; {'message':'helloworld'}) its passed well and I see its logged. So whats wrong with this ajax call that i used in reactjsapp ?
Edited: it looks all parameters passed in browser fine but somehow nodejs unable to get them..
Since POST data is sent in the HTTP body, you need to parse the JSON in there to get it. Assumed you use express.js on the server side, you could use body-parser to do that:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Resources