Recreate a post request in postman - express

I have the following javascript code, to produce a post request.
var postUrl = "http://localhost:3100/radiance";
xhttp.open("POST", postUrl, true);
xhttp.setRequestHeader('Content-type', 'application/json');
let radFile = {"radfile":"long string"}
let solarJson = {"key1":"value1","key2":"value2"}
let latitude = 45
let longitude = 24
msgJson=JSON.stringify({'radFile':radFile,'speedSolar':solarJson,'latitude':latitude,'longitude':longitude})
xhttp.send(msgJson);
The post request works absolutely fine with my express app code below.
var express = require('express');
// require our dependencies
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var port = process.env.PORT || 3100;
var corsOptions = {
credentials: false
};
// use body parser
app.use(bodyParser.urlencoded({extended: true, limit: 1024 * 1024 * 10000, parameterLimit: 1000000*1000}));
app.use(bodyParser.json({type: 'application/json', extended: false, limit: 1024 * 1024 * 10000, parameterLimit: 1000000*1000}));
// route our app
var router = require('./app/routes');
app.use('/', router);
var server
// start the server
server = app.listen(port, function() {
console.log('app started ' +port );
});
However I am struggling to replicate the post request above in post man for testing (purposes).
I believe that the following post request should do the trick but when my app recieves this post request the body of the request is always empty. Why? It seems that the body parser isnt doing it's job.
What I am doing wrong in my post request in postman, how can I replicate my javascript post request exactly?

You are doing two different types of request here. Your website code is sending a JSON string with the contents of the 'files' embedded into it:
let radFile = {"radfile":"long string"}
let solarJson = {"key1":"value1","key2":"value2"}
let latitude = 45
let longitude = 24
msgJson=JSON.stringify({'radFile':radFile,'speedSolar':solarJson,'latitude':latitude,'longitude':longitude})
gives you a body of
{'radFile': {"radfile": "long string"}, 'speedSolar': {"key1":"value1", "key2":"value2"}, 'latitude': 45, 'longitude': 24}
However, when you are using Postman as you are, you are submitting 2 different pieces, a file (or 2) and the form values - you can use the postman echo site to see what you are actually submitting, in case you have questions in the future:
If you really want to replicate your original version, you can do this - a raw body of type json, and fill in the details:

Related

How to retrieve form-data values in Express js?

I created a form data in Postman and send a http post request. but when I send the request, it shows there is no form data in the destination!
here is my codes in backend :
app.js file:
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var routesImagesApi = require('./api/routes/imagesrouters');
app.use('/api/images', routesImagesApi);
api/routes/imagesrouters.js file:
var router = express.Router();
var ctrlAuth = require('../controllers/images');
router.post('/imageUpload', ctrlAuth.imageUpload);
controllers/images.js file:
module.exports.imageUpload = function (req, res) {
res.status(200);
res.json({"Returned data":req.body});
}
I created a request in postman with two key-value form-data body.
here is my request:
POST > http://localhost:3000/api/images/imageUpload
and form-data body key-values are these :
key:name , value:Sarah
key:family , value:Thomas
Below image is Postman screenshot :
I expected postman show me the form-data key values but as you can see it shows nothing!
{
"Returned data": {}
}
Do you have any idea?
Please use the multer package or you could write a custom handler for making express handle multi part form data i.e "files/imgs..etc "
multer package
and
writing your own custom handler
p.s this could be a duplicate issue

How can I read the LtpaToken2 token from my XMLHttpRequest response?

I'm trying to debug another developers code which looks like this:
xhr.open("POST", url, true, this.state.userid, this.state.password);
xhr.withCredentials = true;
xhr.onload = () => {
console.log("here is our packet " + JSON.stringify(xhr));
if (xhr.status === 200) {
var test = xhr.getAllResponseHeaders();
var respoheader = JSON.stringify(xhr.responseHeaders);
var token = respoheader.substring(
respoheader.indexOf("LtpaToken2"),
respoheader.indexOf(
";",
respoheader.indexOf("LtpaToken2")
)
);
console.log("token is parsed ===" + token);
When I run this query from Postman I see two "Set-Cookie" headers added to the response, and one has the content "LtpaToken2=YpMnhu...", which is apparently what I need to grab. But when I run the code above, it does not include this header. I apparently need to grab this token for future calls to another API.
Can someone explain what I'm doing wrong? How can I capture this token, or how am I supposed to connect to another API without this token? As it seems to always be the case with IBM tech, I can find almost ZERO documentation about LtpaTokens.

Google app api with freshdesk api error

On using the freshdesk api from google app script getting an error
"{"code":"invalid_content_type","message":"Content-Type header is set to . It should be set to application/json"}"
The code used for this
function hd_getTickets(){//using v2
var API_KEY = 'xxxxxxxxxxxxxx';
var headers = {'Content-type': 'application/json','Authorization': 'Basic ' + Utilities.base64Encode(API_KEY + ':X') };
var data = { "query":"\"priority:3\"" };
var ENDPOINT = 'https://xxxxxxx.freshdesk.com/api/v2';
var url = ENDPOINT + '/search/tickets';
var options = { 'method': 'get', muteHttpExceptions: true,'headers': headers,'payload' : JSON.stringify(data)};
var response = UrlFetchApp.fetch(url, options);
}
Changing the endpoint and removing the payload from options work so assuming authorization and header is fine
var url = ENDPOINT + '/tickets';
var options = {'method':'get','headers':headers, muteHttpExceptions: true};
Using postman this works
https://xxxxxxx.freshdesk.com/api/v2/search/tickets?query="priority:3"
with header set as
Content-Type:application/json
Authorization:Basic xxxxxxxxxxxxxxxx
You are sending a GET request to the API with the Payload variable in the options.
In my opinion payloads are used for POST requests.
Construct the URL with the query parameters and send it without the Payload.
Example: 'https://domain.freshdesk.com/api/v2/search/tickets?query="priority:3"'
See details here: HTTP GET with request body
Freshdesk API Doc: https://developers.freshdesk.com/api/#filter_tickets
Two issues found
1) web site does not support payload based get.
2) google apps doesn't support special characters in url.
Adding parameters to the original url and encoding the double quotes works.
var ENDPOINT = 'https://xxxxxx.freshdesk.com/api/v2';
var query ='query='+encodeURIComponent("\"priority")+":1"+encodeURIComponent("\"");
var url = ENDPOINT + '/search/tickets?'+query;
var options = {'method': 'get', muteHttpExceptions: true,'headers': headers};
var response = UrlFetchApp.fetch(url, options);

No response from Express + postman

I cannot seem to POST data via Postman & Express.
My POST verb code is as follows
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var fdbRouter = express.Router();
fdbRouter.route('/films')
//post verb
.post(function (req, res) {
var item = new Film(req.body);
console.log(item);
//item.save();
res.status(201).send(item);
})
And my Postman setup is as follows
I have befriended google and came up with this
1. Node.js/Express form post req.body not working
2. req.body empty on posts
3. Express + Postman, req.body is empty
4. `express` app - not able to test the `post` request using `postman`
PS The watched item in postman is default in the mongoose schema i have so it's created regardless whether express works or not.
Whenever I have worked with a post request in express it's been formatted as below (assuming you're using mongoDB):
var express = require('express');
var fdbRouter = express.Router();
var model = require("<FILE TO IMPORT MODEL>") //This file will differ, but you need to import the model you created for films in your DB
var FilmModel = model.Film //also depends on how you exported your model in your dbFiles. Either way you need this model as the blue print for your post request
//I'm also assuming here that you're calling /films correctly and have it sourced as such in your app.js so you don't need /api/films as you have listed in your postman setup image
fdbRouter.post('/films', function(req,res){
var newfilm = new FilmModel()
newFilm.title = req.body.Title
newFilm.year = req.body.Year
newFilm.genre = req.body.Genre
newFilm.save(function(err, savedObject){
if(err){
console.log(err)
res.status(500).send()
}else{
res.send(savedObject)
}
})
})
Please note: this code example assumes a test db with a schema and model has been setup and is available for import to your routes file.
Let me know if this puts you on the right track!

body-parser does not work, req.body is undefined [duplicate]

I can't seem to recover the form-data of a post request sent to my Node.js server. I've put below the server code and the post request (sent using postman in chrome):
Post request
POST /api/login HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="userName"
jem
----WebKitFormBoundaryE19zNvXGzXaLvS5C
NodeJS server code
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser());
app.all('/*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,accept,access_token,X-Requested-With');
next();
});
var port = process.env.PORT || 8080; // set our port
var router = express.Router(); // get an instance of the express Router
router.get('/', function(req, res) {
res.json({ message: 'I am groot!' });
});
// Login
router.route('/login')
.post(function(req, res){
console.log('Auth request recieved');
// Get the user name
var user = req.body.userName;
var aToken = getToken(user);
res.json({
'token':'a_token'
});
});
app.use('/api', router);
app.listen(port);
The login method tries to obtain the req.body.userName, however, req.body is always empty.
I've seen other cases on SO describing such behavior but none of the related answers did apply here.
Thanks for helping out.
In general, an express app needs to specify the appropriate body-parser middleware in order for req.body to contain the body.
[EDITED]
If you required parsing of url-encoded (non-multipart) form data, as well as JSON, try adding:
// Put this statement near the top of your module
var bodyParser = require('body-parser');
// Put these statements before you define any routes.
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
First, you'll need to add body-parser to the dependencies property of your package.json, and then perform a npm update.
To handle multi-part form data, the bodyParser.urlencoded() body parser will not work. See the suggested modules here for parsing multipart bodies.
I followed this
https://www.tutorialspoint.com/expressjs/expressjs_form_data.htm
var bodyParser = require('body-parser');
var multer = require('multer');
var forms = multer();
// apply them
app.use(bodyParser.json());
app.use(forms.array());
app.use(bodyParser.urlencoded({ extended: true }));
// how to use
router.post('/', function(req, res) {
console.log(req.body);
console.log('received the widget request');
});
To handle multipart/form-data request that support file upload, you need to use multer module. npm link for multer middleware
For Json: Use body-parser.
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
(you should Also send Content-Type: application/json in request header)
For Normal Form, Or multipart form (form with files), Use body-parser + multer.
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(multer().array())
(You should NOT send Content-Type: application/json in this case. you should send nothing, or Content-Type: multipart/form-data if you have files in form.
in postman you should not send Content-Type: multipart/form-data manually. otherwise you'll get an error (Boundary not found). (it will add this automatically.).)
Make sure to put in this order:
bodyParser.json() first.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Make sure you are not sing enctype as multipart/form-data, body parser does not support it.
use below line before you define any route.
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());