I am working on retrieving a post request body so that i can add the arguments in the body to my database.
At first I was getting an error SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>) but i added this line applctn.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies and now i get an empty body.
My code looks like this :
const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");
const applctn = express();
applctn.use(bodyParser.urlencoded({extended: true}));
applctn.post("/hl7_message", function(req, res) {
var jsonObj = JSON.stringify(req.body);
console.log(req);
When i add ```app.use(bodyParser.json()); // to support JSON-encoded bodies
```SyntaxError: Unexpected token ' in JSON at position 0 at JSON.parse (<anonymous>)
Any advise /tips on how i can retrieve the body contents will be appreciated.
my response
You forgot to add applctn.use(bodyParser.json()). Here is the solution :
const express = require("express");
const moment = require("moment");
const db = require("./dbconnection.js"); //reference of dbconnection.js
var bodyParser = require("body-parser");
const applctn = express();
applctn.use(bodyParser.json());
applctn.use(bodyParser.urlencoded({extended: true}));
applctn.post("/hl7_message", function(req, res) {
console.log(req.body);
res.send({code:200,message:"success"})
})
applctn.listen(3000,function(){
console.log("running");
});
Related
I am making an express application that handles post data. Because the request body could be any content type and/or binary, I would like req.body to be a Buffer. So what should I use to get a Buffer that represents the request body? Here is my code:
import express from "express";
const app = express();
app.get("/", (req, res) => {
// Get request body as buffer
// Do something with the buffer
});
body-parser can help achieve this, code example would be as,
import express from 'express';
const bodyParser = require('body-parser');
const app = express();
const options = {
type: 'application/octet-stream',
};
app.use(bodyParser.raw(options));
app.get('/', (req, res) => {
const bufferObject = req.body; // Get request body as buffer
// Do something with the buffer
});
See more details about Raw body parser and default options needs to be supplied - bodyParser.raw([options])
I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine
I am trying to build a simple search form in Express using the Amadeus api. I can see the data returned to the console but upon clicking the search button on my index.js the page keeps giving me http://localhost:3001/results/undefined?q=CPT&submit= and doesn't resolve.
What am I missing here please? How do I access the response in key form to build my result page? Any help would be greatly appreciated!
app.js
require('dotenv').config();
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const indexRouter = require('./routes/index');
const postRouter = require('./routes/post');
const resultsRouter = require('./routes/results');
const usersRouter = require('./routes/users');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/', postRouter);
app.use('/', resultsRouter);
app.use('/users', usersRouter);
module.exports = app;
Index.js
extends layout
block content
h1= title
div.container-fluid
div.row.justify-content-center
p Find Your Dream Kruger Safari Package!
form.form-inline.my-2.my-lg-0#searchBox(
action='/results/' + q
method='GET'
)
input.form-control.mr-sm-2(type='text', placeholder='City Code ie. LON, JHB, CPT', aria-label='Search', id='q' name='q' required)
button.btn.btn-success.my-2.my-sm-0(type='submit' id='submit' name="submit") Search
results.js
const express = require('express');
const router = express.Router();
router.get('/results/:q', (req, res) => {
const q = req.query.q;
// const result = ;
// q = JSON.stringify(q);
// console.log(result);
const searchAmadeus = require('../controllers/amadeusControl.js');
searchAmadeus.findNew(q, (err, docs) => {
if (!err) {
res.render('results', {
title: 'We Found Some Great Deals',
list: docs,
});
} else {
console.log('Error finding record :' + err);
}
});
});
module.exports = router;
post.js
const express = require('express');
const router = express.Router();
router.post('/results/:q', function(req, res) {
const q = req.body.q;
res.send(q);
// res.send(q);
//console.log(q);
});
module.exports = router;
results.pug
extends layout
block content
h1= title
p Results
div.find test #{body}
div.container
div.row
div.col-sm
p left col content
div.col-sm
tbody
each docs in list
tr
td= doc
amadeusControl.js
module.exports = {
findNew: function(q) {
// const bodyParser = require('body-parser');
// initialize the client and authenticate
const Amadeus = require('amadeus');
// console.log(process.env.AMADEUS_CLIENT_ID);
const amadeus = new Amadeus({
'clientId': process.env.AMADEUS_CLIENT_ID,
'clientSecret': process.env.AMADEUS_CLIENT_SECRET,
});
// Get list of Hotels by city code
amadeus.shopping.hotelOffers.get({
cityCode: q,
}).then(function(response) {
// console.log(response.body); // => The raw body
console.log(response.result); // => The fully parsed result
// console.log(response.data); // => The data attribute taken from the result
docs = response.result;
}).catch(function(error) {
console.log(error.response); // => The response object with (un)parsed data
console.log(error.response.request); // => The details of the request made
console.log(error.code); // => A unique error code to identify the type of error // END Do something with the returned data.
});
}};
First of all, you would access the :q parameter using the req.params object, not the req.body.
But, I think you want to use req.query instead.
Express req.query docs
If you want to use the req.body, you will need to change your form to a POST request instead of a GET request.
I am trying simple api which return sml response :
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const libxmljs = require("libxmljs");
const PORT = process.env.PORT || 5000;
const app = express()
app.use(cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send({ "message": "success" });
});
app.get('/api', (req, res) => {
var libxmljs = require("libxmljs");
var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<root>' +
'<child foo="bar">' +
'<grandchild baz="fizbuzz">grandchild content</grandchild>' +
'</child>' +
'<sibling>with content!</sibling>' +
'</root>';
var xmlDoc = libxmljs.parseXml(xml);
// xpath queries
var gchild = xmlDoc.get('//grandchild');
console.log(gchild.text()); // prints "grandchild content"
var children = xmlDoc.root().childNodes();
var child = children[0];
console.log(child.attr('foo').value()); // prints "bar"
res.set('Content-Type', 'text/xml');
res.send(xmlDoc);
});
app.listen(PORT, () => {
console.log(`App running on PORT ${PORT}`)
});
here everthing is showing as expected in node console, but in the APi response i am not getting XML, I am getting this error:
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
Please help
I see that you copy the code from github repo.
You're sending as response the xml object, not the string....
Instead of
res.send(xmlDoc);
do
res.send(xml);
This is my index.js file and i think i have placed the routes after installing bodyParser but still getting the syntax error.
const express = require('express'); //Framework to build server side application
const morgan = require('morgan'); //Logging the nodejs requests
const bodyParser = require('body-parser'); //To get the JSON data
const urls = require('./db/urls');
const app = express();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(express.static('./public')); //If a request comes with '/' check if file is in there if it is then serve it up.
// app.get('/', (req, res) => {
// res.send('Hello, World !!');
// });
app.post('/api/shorty', async (req, res) => {
console.log(req.body);
try {
const url = await urls.create(req.body); //Passing the body data which is JSON to create function
res.json(url);
} catch (error) {
res.status(500);
res.json(error)
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
This is the urls.js file,I am not getting where have i messed up to make Syntax.JSON error in this file.
const db = require('./connection');
const Joi = require('joi');//Schema validation
const urls = db.get('urls');
const schema = Joi.object().keys({
name : Joi.string().token().min(1).max(100).required(),
url : Joi.string().uri({
scheme: [
/https?/ //get http 's' is optional
]
}).required()
}).with('name','url');
//almostShorty = {
// name = ,
// url =
// }
function create(almostShorty){
const result = Joi.validate(almostShorty, schema);
if(result.error === null){
return urls.insert(almostShorty);//Inserting the object in the Data Base.
}else{
return Promise.reject(result.error);
}
};
module.exports = {create};//Exporting the create function.