I'm trying to receive a callback from the Dribbble Auth API. The Authentication process is working fine until I'm trying to fetch the response data with NodeJS.
My Callback-URL is http://localhost:8080/callback
A callback url looks like this http://localhost:8080/callback?code=11ee328ab7935bd7240cbff0a2d0b8c93e96547e0a3&state=aoksdmSAOKDm
I'm using body-parser and multer.
var express = require("express");
var multer = require("multer");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var upload = multer({ storage: multer.memoryStorage() });
var app = express();
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "../webapp/")));
app.get("/callback", upload.single("code"), (req,res) => {
console.log(req.body);
res.send()
}
The response in the console is undefined
the query isn't in req.body with a GET request. you have to do:
req.query
You are sending a GET request.Please check
req.query
More details refer
http://expressjs.com/en/api.html
Related
Here I have created the small demo for this form-data passing API. Now I'm checking this API using postman but I'm not getting any data.
Code
const http = require("http");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.json({
limit: "50mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "50mb",
extended: true
})
);
app.post('/form-data', (req, res) => {
console.log("form-data ->> ", req.body)
});
server = http.createServer(app);
server.listen(4000[![enter image description here][1]][1], () => {
console.log(`Server started`);
});
Server log
Server started
form-data ->> {}
Header
I tried to reproduce your code with small changes.
const express = require("express");
const bodyParser = require("body-parser");
var multer = require("multer");
var upload = multer();
const app = express();
// for parsing application/json
app.use(
bodyParser.json({
limit: "50mb",
})
);
// for parsing application/xwww-form-urlencoded
app.use(
bodyParser.urlencoded({
limit: "50mb",
extended: true,
})
);
// for parsing multipart/form-data
app.use(upload.array());
app.post("/form-data", (req, res) => {
console.log(`\nform-data ->> ${JSON.stringify(req.body)}`);
res.send(req.body);
});
const port = 3000;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
I removed your server initialization since we can use app listen directly from the expressjs.
And I can send post with "form-data", "x-www-form-urlencoded", or "raw" successfully.
You might double-check on which tutorial you following. Since express documentation is clear enough.
*Edited
I added multer to parsing the form-data.
if you are using multer as middleware on the post route with other middle middlewares put the multer middleware first.
app.post(
"/api/private/buyer/add-buyer",
[
upload, verifySignUp.checkDuplicateUsernameOrEmail,
],
controller.createBuyer
);
here upload is multer middleware I put it first it works for me.
I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:
This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried. My current implementation goes like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()
//Import static files
app.use(express.static('../public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', jsonParser, (req, res) => {
console.log(req.body);
res.send(200);
});
app.listen(port, () => console.log("Server started"));
No matter what I try from other posts, it still does not seem to return me any data.
Does anyone have an idea how to fix this problem?
Why to you use 'jsonParser' in the app route? Try something like:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post-test', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});
To set up my bodyparser I use the following code:
const express = require('express')
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
Now if I have the following POST route in my express router:
var router = require('express').Router();
router.post('/sendadvertisement', async (req, res) => {
console.log(req.body)
});
The result is [Object: null prototype] {advertisement: 'test'}
-> My req.body isn't empty because it's in json format in my console output.
I don't really understand how this result can happen because I defined that the body should be in json format.
I also tried it with app.use(express.json()), doesn't work either.
I replaced router with app and everything worked fine.
Router.get/post etc is only for defining sub routes after after you mounted a middelware function like app.use('route') that handels the Route. If you want to use the router you should mount the route using app.use(...) and then declare the post using router.post(...)
Also See: Difference Between app.use() and router.use() in Express
const express = require('express')
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.post('/sendadvertisement', async (req, res) => {
console.log(req.body)
});
app.listen(8000, () => {
console.log('Example app listening on port 8000!')
});
If you are using express then you can use this code to set your body parser.
app.use(express.json( {extended:false} ));
app.use(express.urlencoded({extended: false}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
This is also giving error, page is scrolling after submission.
I've got a simple Express server that uses the body-parser module to access POST-parameters. The app looks like this:
/index.js:
'use strict';
const express = require('express');
const app = express();
const apiRouter = require('./api/routes.js');
// Set our port for the server application
const port = process.env.PORT || 8080;
// Register the routes for the /api prefix
app.use('/api', apiRouter);
// Start server
app.listen(port);
console.log('The server is running on port ' + port);
/api/routes.js:
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Configure app to use bodyParser(). This will let us get the data from a POST
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
// START ROUTES
router.post('/devices', (req, res) => {
console.log(req.body); // Returns {}
res.json(req.body);
});
module.exports = router;
The problem is that the req.body object is empty (Always returns an empty object {}). Since I already loaded the body-parser middleware I have no idea what else I can try. I hope you have any suggestions.
I used the app Postman for testing. It appeared that it sent the POST data as form-data instead of x-www-form-urlencoded. After changing this setting the data showed up.
Trying to access the body of an incoming text message with Twilio.
var express = require('express');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
...
module.exports = function(app) {
...
app.post('/twilio/message', jsonParser, function(request, response) {
var twiml = new twilio.TwimlResponse();
twiml.message('test body is ' + request.Body);
// I also tried JSON.stringify(request.body) to see what was in body and it returned '{ñ'
response.type('text/xml');
response.send(twiml.toString());
});
}
The following returns 'test body is undefined'. Not sure what I'm doing wrong the request data seems to be there and I can access request.url.
Edit: Question updated with attempt to use body-parser library.
I'm taking Twilio out of this equations (it's not the issue here). Also remember to npm install body-parser --save.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// listen for POSTs on /twilio/message
app.post('/twilio/message', function(req, res){
console.log(req.body);
res.end("End");
});
// start express
app.listen(8888);
You can test this with Postman (make sure you set x-www-form-urlencoded as your body data (or use raw with application/json) to test.
I just did to make sure it works.
I've worked with Twilio in the past and this is exactly the code we used to parse the body.