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);
Related
I have a simple node script in which I update the db.json file through the form. It updates the file but when I render it in response for a get or post out it gives previous results only.
var cors = require('cors')
const express = require('express');
const app = express();
var jsonfile = require('jsonfile');
var file = './db.json'
var filex = require('./db.json')
app.engine('html', require('ejs').renderFile);
app.use(cors())
const http = require('http');
const port = process.env.PORT || 3000
const bp = require('body-parser')
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))
app.set('view engine', 'html')
// Defining get request at '/' route
app.get('/', function(req, res) {
res.send("<html><head><title>Json</title></head><body><form id='form1' action='/gettingdata' method='post'><input type='text' name='usrid' /><button type='submit' form='form1' value='Submit'>Submit</button></form></body></html>")
});
app.post('/gettingdata',function(req,res){
var user_id = req.body.usrid;
var obj = JSON.parse(user_id)
jsonfile.writeFileSync(file, obj,{flag: 'w'});
res.send('updated');
})
app.post('/api',function(req,res){
res.send(filex)
})
app.get('/api',function(req,res){
res.send(filex)
})
//extra
app.post('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.get('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.listen(port, function(req, res) {
console.log("Server is running at port 3000");
});
It only gives updated results on redeveloping of server.
var filex = require('./db.json')
So, filex only load the file when the server starts. If you try to get the most updated content of file db.json, please re-load the file.
I guess res.send(require('./db.json')) may work as expected.
I have solved this issue using
delete require.cache[require.resolve('./db.json')]
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");
});
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.
I am sending data using swift to a nodeJS server.
Here is the Swift Code:
var data:[String:String] = [:]
data["ABC"] = "nothing"
let req = HTTPRequest(url_to_request: "https://xxx.xxx.xx.x/update", method: HTTPRequest.HTTPRequestMethod.post, data: Profile.toJSON(dict: data))
Here is the NodeJS:
console.log("Server is up!");
var bodyParser = require('body-parser');
var express = require('express');
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var http = require('http');
var https = require('https');
var fs = require('fs');
var bcrypt = require('bcryptjs');
var sslOptions = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('cert.pem', 'utf8'),
passphrase: 'phrase',
rejectUnauthorized: false
};
var app = express();
//Variables:
var httpPort = 8888;
var httpsPort = 8443;
app.use(bodyParser.urlencoded({
extended: false,
limit: '20mb'
}));
app.use(bodyParser.json({
limit: '50mb'
}));
// parse application/json json size limit
// parse application/x-www-form-urlencoded
// setup server
app.set("port_https", httpsPort);
//check secure connection
app.all("*", function(req, res, next) {
console.log("Secure connection: " + req.secure);
if (req.secure) {
return next();
}
res.redirect("https://" + req.hostname + ":" + app.get("port_https") + req.url);
});
// add User
app.post('/register', register);
//signIn
app.post('/login', logIn);
//Update user's profile details.
app.post('/update', updateProfile);
// Request profile details.
app.post('/profile', profileRequest);
function updateProfile(req, res) {
console.log(res.body); // ---> undefined
}
When I send a post request with data to login, profile, register routers res.body is working well. But when I send data to update for some reason req.body is undefined:
ERROR:
Server: Secure connection: true
Server: undefined #----> log of res.body
Server: Connected successfully to databse!
stderr: /home/asaf/NodeJS/IBQA/IBQA_Server/node_modules/mongodb/lib/mongo_client.js:350
throw err
^
TypeError: Cannot read property 'ABC' of undefined
at /*****/server.js:92:33
at connectCallback (*****/mongo_client.js:428:5)
at /*****/node_modules/mongodb/lib/mongo_client.js:347:11
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
closing code: 1
Your request if there in the req variable, res is used to send the response. Try console.log(req.body)
Well I had just started programming in node.js. I am stuck at one place.
I am getting my request parameter like
response: --------------------------e2a4456320b2131c
sent
--------------------------e2a4456320b2131c
Content-Disposition: form-data; name="is_test"
true
--------------------------e2a4456320b2131c
Content-Disposition: form-data; name="success"
true
--------------------------e2a4456320b2131c--
How can i fetch all this params :
is_test , success and etc.
Here is my code :
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
exports.helloWorld = functions.https.onRequest((request, response) => {
var body = "";
request.on('data', function (data) {
body += data;
});
request.on('end', function() {
console.log('response: ' + body);
});
);
You need to configure the router to handle the request. Take a look at the hello world example of express docs http://expressjs.com/en/starter/hello-world.html
Moreover if you are sending data in the body you are looking for a http post method.
Example:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
app.post('/', function (req, res) {
const body = req.body;
/*Body logic here*/
res.status(200).end();
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
})