Getting status 200 but no response in body - javascript

Here is my service call
<script>
function secureClicked() {
var uname = document.getElementById('uname').value;
var pwd = document.getElementById('pwd').value;
var obj = new Object();
obj.username = uname;
obj.password = pwd;
var userObj = JSON.stringify(obj);
xhr = new XMLHttpRequest();
var url = "http://127.0.0.1:9923/login";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
document.write(json.accesstoken);
onComplete(xmlhttp.responseText);
}
};
xhr.send(userObj);
}
Here is my backend code
module.exports = {
login: function(req, res) {
MongoClient.connect(mongoUrl, function (err, db) {
if (err) {
console.log('into error of mongo');
res.status(400).json({
message: 'Connection to database failed !!',
error: err
});
}
insertDocument(db, req.body, function (result) {
console.log('into insert doc');
res.setHeader('Content-Type', 'application/json');
res.status(200).json({
access_token: result._id
});
});
});
var insertDocument = function (db, data, callback) {
console.log('into insert doc function');
console.log(data);
var string = JSON.stringify(data);
var objectValue = JSON.parse(string);
var username = objectValue['username'];
var password = objectValue['password'];
console.log(username);
db.collection('user_list').findOne({$and:[{ 'username':username},{'password':password}]}, function(err, result) {
if (err) {
res.status(500).json({
message: 'Failed to add in DB!!'
});
} else {
callback(result);
}
});
}
}
};
I'm able to get response in postman, but unable to get response in browser.
Am I doing anything worng here ?
Can anyone help me on this?
Thanks in advance !!

Related

AXIOS POST return result

I have created a non-JWT api call and it works. The moment I added JWT verifyToken it works but I cannot seems to get the return result set from AXIOS POST.
Function 2 --> /userget ----is working I can display result on HTML
Function 7 ---> /api/userget ---It can get data and token but I cannot display on HTML, it goes to "Bad response"
++++++++++++++++++++++++++++++++
function myFunction2() {
console.log("Going2");
var userid = document.getElementById("userid").value;
console.log(userid);
axios( {
method: 'post',
url:'http://localhost:8081/userget',
data : {
userid : userid
}
})
.then(function (response) {
console.log(response.data.result[0].username );
var userid = JSON.stringify(response.data.result[0].userid);
var username = JSON.stringify(response.data.result[0].username);
var email = JSON.stringify(response.data.result[0].email);
var userid = JSON.parse(userid);
var username = JSON.parse(username);
var email = JSON.parse(email);
var displaydata = ("User ID : " + userid + "<br><br>Name : " + username + "<br><br>Email :" + email);
document.getElementById("demo").innerHTML = displaydata;
})
.catch(function (error) {
document.getElementById("demo").innerHTML = "Bad response";
});
}
+++++++++++++++++++++++++++++++++
function myFunction7() {
console.log("Going7");
var userid = document.getElementById("userid").value;
console.log(userid);
console.log("Print local token == " + localStorage.getItem("token"));
var msgtxt = localStorage.getItem("token");
axios( {
method: 'post',
url:'http://localhost:8081/api/userget',
headers: {
'Authorization': `Bearer ${msgtxt}`
},
data : {
userid : userid
}
})
.then(function (response) {
console.log(response.data.result[0].username );
var userid = JSON.stringify(response.data.result[0].userid);
var username = JSON.stringify(response.data.result[0].username);
var email = JSON.stringify(response.data.result[0].email);
var userid = JSON.parse(userid);
var username = JSON.parse(username);
var email = JSON.parse(email);
var displaydata = ("User ID : " + userid + "<br><br>Name : " + username + "<br><br>Email :" + email);
document.getElementById("demo").innerHTML = displaydata;
})
.catch(function (error) {
document.getElementById("demo").innerHTML = "Bad response";
});
}
+++++++++++++++++++++++++++++
app.post('/userget', function (req, res) {
const userid = req.body.userid;
console.log ("User id == " + userid)
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({result})
} else{
res.send(err.errno + " No record");
}
res.end()
});
});
+++++++++++++++++++++
app.post('/api/userget', verifyToken, (req, res) => {
const userid = req.body.userid;
console.log ("User id == " + userid)
jwt.verify(req.token, secretKey, (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({result})
} else{
res.send(err.errno + " No record");
}
res.end()
});
res.json({
message: 'Post created...',
authData : authData
});
}
});
});
Error in terminal
/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:267:15)
at ServerResponse.send (/home/ronaldtan/Programming/webservices/node_modules/express/lib/response.js:158:21)
at /home/ronaldtan/Programming/webservices/controller/app.js:170:17
at Query. (/home/ronaldtan/Programming/webservices/model/user.js:44:32)
at Query. (/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/Connection.js:526:10)
at Query._callback (/home/ronaldtan/Programming/webservices/node_modules/mysql/lib/Connection.js:488:16)
The problem is the following:
user.getUser(userid, function (err, result) {
if (!err) {
console.log(result)
res.send({
result
})
} else {
res.send(err.errno + " No record");
}
res.end()
});
res.json({
message: 'Post created...',
authData: authData
});
The second statement (res.json(...)) is executed before the async-operation user.getUser(..) has finished. So once its callback is executed, res.json will already have finished and since you are trying to res.send again (res.json does the same operation under the hood) you get the error.
It seems like you can just remove the res.json(...) statement as you want to return the found user, not some info about creating a post.

why is the request post not running

I am currently encountering some issues where request.post() is not running. Somehow my code is skipping both the request.post() in the if and else statements. Could anyone advise what I did wrong or how to improve my code? It would great if someone also explains to me what I did wrong.
CurrentOrder.findOneAndUpdate(_id, orderBody, function (err, data) {
if (err) return next(err)
CurrentOrder.findOne(_id2, function(err, order) {
if (err) return next(err)
if(order.canadaTrackingStatus.length == 1 && orderBody.paymentStatus == 'paid'){
order.canadaTrackingStatus = [order.canadaTrackingStatus[0], {date: new Date(), status: '门店已揽收'}];
order.save(function(err) {
if (err) return next(err)
var modItems = merge_items(order.items)
var url = {OrderCode:order.orderNumericCode,Sender:{Name:order.senderName,Tel:order.senderPhone,ProvinceName:order.senderProvince,CityName:order.senderCity,ExpAreaName:order.senderCity,Address:order.senderAddress},Receiver:{Name:order.recipientName,Tel:order.recipientPhone,ProvinceName:order.recipientProvince,CityName:order.recipientCity,ExpAreaName:order.recipientCity,Address:order.recipientAddress},Content:modItems}
var newurl = encodeURI(JSON.stringify(url))
console.log(newurl)
request.post({
headers: { 'Content-Type':'content=text/html;charset=utf-8' },
url : `http://rrr.cn/order/create?EBusinessID=1afs190&AppKey=trytr5fasfasf68980hg23gff&Sign=a1a4e30c83c8c9e6d6fd1fasfasfac55dbc1f2f&RequestType=100232&RequestData=${newurl}`
},function(error,response,body){
var chinacode = JSON.parse(body).logisticcode
var newbody = Object.assign(order, {vipOrderNumericCode : chinacode})
CurrentOrder.findOneAndUpdate({_id:order._id}, newbody, function (err, data2) {
if(err) return next(err)
console.log('if')
})
})
});
}else if(order.canadaTrackingStatus.length == 1 && orderBody.paymentStatus == 'pending'){
order.canadaTrackingStatus = [order.canadaTrackingStatus[0]];
order.save(function(err) {
if (err) return next(err)
var modItems = merge_items(order.items)
var url = {OrderCode:order.orderNumericCode,Sender:{Name:order.senderName,Tel:order.senderPhone,ProvinceName:order.senderProvince,CityName:order.senderCity,ExpAreaName:order.senderCity,Address:order.senderAddress},Receiver:{Name:order.recipientName,Tel:order.recipientPhone,ProvinceName:order.recipientProvince,CityName:order.recipientCity,ExpAreaName:order.recipientCity,Address:order.recipientAddress},Content:modItems}
var newurl = encodeURI(JSON.stringify(url))
console.log(newurl)
request.post({
headers: { 'Content-Type':'content=text/html;charset=utf-8' },
url : `http://rrr.cn/order/create?EBusinessID=11987650&AppKey=trytr56809876980hg23gff&Sign=a1a4e30c83c8c9e6d6fd10987ac55dbc1f2f&RequestType=1002&RequestData=${newurl}`
},function(error,response,body){
var chinacode = JSON.parse(body).logisticcode
var newbody = Object.assign(order, {vipOrderNumericCode : chinacode})
CurrentOrder.findOneAndUpdate({_id:order._id}, newbody, function (err, data2) {
if(err) return next(err)
console.log('else')
})
})
});
}
});
if (req.user.userRole == 'admin') {
if (data.batch) res.redirect('/admin/view-batches')
else res.redirect('/admin/orders')
} else {
return res.redirect('/client/current')
}
})

node.js: deasync never returning

In node.js I'm using deasync to return the result of a request query.
var request = require('request');
var deasync = require("deasync");
const URL_1 = "...", URL_2 = "...", USER_AGENT = "...";
function getHtml() {
function requrl(url, form) {
return {
url: url,
headers: {'User-Agent': USER_AGENT},
form: form,
jar: true
}
}
var form = {email:"email#geemail.com", password:"thepass"};
var resp;
request.post(requrl(URL_1, form), function (error, response, body) {
if (error || response.statusCode != 200) {
resp = error;
} else {
request(requrl(URL_2), function (error, response, body) {
console.log(response); // <- this makes it work
if (error || response.statusCode != 200)
resp = error;
else
resp = body;
})
}
})
while (resp === undefined) deasync.runLoopOnce();
return resp;
}
This works fine. But if i remove this line: console.log(response); it never returns. I have no idea what is going on.

how to grab data within a JSON string

Hi all I am trying to display the words "hello JSON" on my web page but it's displaying the full string { "msg": "Hello JSON." }. I know why it is doing that, but how can I get it to display just hello JSON without just plopping it into an html script and using just that?
This is my code:
var http = require('http');
var domain = require('domain');
var root = require('./message'); // do I have to replace root w/ message
var image = require('./image'); // for better readability?
function replyError(res) {
try {
res.writeHead(500);
res.end('Server error.');
} catch (err) {
console.error('Error sending response with code 500.');
}
};
function replyNotFound(res) {
res.writeHead(404);
res.end('not found');
}
function handleRequest(req, res) {
console.log('Handling request for ' + req.url);
if (req.url === '/') {
root.handle(req, res);
}
if (req.url === '/image.png'){
image.handle(req, res);
} else {
replyNotFound(res);
}
}
var server = http.createServer();
server.on('request', function(req, res) {
var d = domain.create();
d.on('error', function(err) {
console.error(req.url, err.message);
replyError(res);
});
d.run(function() { handleRequest(req, res)});
});
server.listen(5000);
then message.js or root (in min var root = require(/message)
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': body.length
});
res.end(body);
};
exports.init = function(cb) {
require('fs').readFile('app.html', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}
app.html
<html>
<header><title>This is title</title></header>
<body>
Hello world
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('message.js'); };
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send(msg);
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
</body>
</html>
Try changing body = data; to body = data.msg; in you 'message.js' file. This will lookup the value for the key, msg, in the JSON object and assign the result to the body variable.
edit
In your alertContents function, replace:
alert(httpRequest.responseText);
with:
var resData = JSON.parse(httpRequest.ResponseText);
alert(resData.msg);
What this does is parse the JSON response into a Javascript object and then looks up the msg attribute and uses that for the alert.
edit 2
Any time that you need to parse JSON, use JSON.parse(jsonString). It will return a native JavaScript object that you can store in a variable and look up attributes on, as in the example above.
I cannot see where you're receiving the msg from but at the place where you receive the JSON string just do this.
var jsonResult = receivedData();
if (jsonResult && jsonResult.msg)
{
alert(jsonResult.msg);}
}

How to use this node.js module in some file

This is my 3rd party node-js module:
var knox = require('knox')
, Resource = require('deployd/lib/resource')
, httpUtil = require('deployd/lib/util/http')
, formidable = require('formidable')
, fs = require('fs')
, util = require('util')
, path = require('path');
function S3Bucket(name, options) {
Resource.apply(this, arguments);
if (this.config.key && this.config.secret && this.config.bucket) {
this.client = knox.createClient({
key: this.config.key
, secret: this.config.secret
, bucket: this.config.bucket
});
}
}
util.inherits(S3Bucket, Resource);
module.exports = S3Bucket;
S3Bucket.label = "S3 Bucket";
S3Bucket.prototype.clientGeneration = true;
S3Bucket.events = ["upload", "get", "delete"];
S3Bucket.basicDashboard = {
settings: [{
name: 'bucket'
, type: 'string'
}, {
name: 'key'
, type: 'string'
}, {
name: 'secret'
, type: 'string'
}]
};
S3Bucket.prototype.handle = function (ctx, next) {
var req = ctx.req
, bucket = this
, domain = {url: ctx.url};
if (!this.client) return ctx.done("Missing S3 configuration!");
if (req.method === "POST" && !req.internal && req.headers['content-type'].indexOf('multipart/form-data') === 0) {
var form = new formidable.IncomingForm();
var remaining = 0;
var files = [];
var error;
var uploadedFile = function(err) {
if (err) {
error = err;
return ctx.done(err);
} else if (!err) {
remaining--;
if (remaining <= 0) {
if (req.headers.referer) {
httpUtil.redirect(ctx.res, req.headers.referer || '/');
} else {
ctx.done(null, files);
}
}
}
};
form.parse(req)
.on('file', function(name, file) {
remaining++;
if (bucket.events.upload) {
bucket.events.upload.run(ctx, {url: ctx.url, fileSize: file.size, fileName: file.filename}, function(err) {
if (err) return uploadedFile(err);
bucket.uploadFile(file.filename, file.size, file.mime, fs.createReadStream(file.path), uploadedFile);
});
} else {
bucket.uploadFile(file.filename, file.size, file.mime, fs.createReadStream(file.path), uploadedFile);
}
})
.on('error', function(err) {
ctx.done(err);
error = err;
});
req.resume();
return;
}
if (req.method === "POST" || req.method === "PUT") {
domain.fileSize = ctx.req.headers['content-length'];
domain.fileName = path.basename(ctx.url);
if (this.events.upload) {
this.events.upload.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.upload(ctx, next);
});
} else {
this.upload(ctx, next);
}
} else if (req.method === "GET") {
if (ctx.res.internal) return next(); // This definitely has to be HTTP.
if (this.events.get) {
this.events.get.run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.get(ctx, next);
});
} else {
this.get(ctx, next);
}
} else if (req.method === "DELETE") {
if (this.events['delete']) {
this.events['delete'].run(ctx, domain, function(err) {
if (err) return ctx.done(err);
bucket.del(ctx, next);
});
} else {
this.del(ctx, next);
}
} else {
next();
}
};
S3Bucket.prototype.uploadFile = function(filename, filesize, mime, stream, fn) {
var bucket = this;
var headers = {
'Content-Length': filesize
, 'Content-Type': mime
};
this.client.putStream(stream, filename, headers, function(err, res) {
if (err) return ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
fn(err || message);
});
} else {
fn();
}
});
};
S3Bucket.prototype.upload = function(ctx, next) {
var bucket = this
, req = ctx.req;
var headers = {
'Content-Length': req.headers['content-length']
, 'Content-Type': req.headers['content-type']
};
this.client.putStream(req, ctx.url, headers, function(err, res) {
if (err) return ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
ctx.done(err || message);
});
} else {
ctx.done();
}
});
req.resume();
};
S3Bucket.prototype.get = function(ctx, next) {
var bucket = this;
var url = 'https://s3.amazonaws.com/' + this.config.bucket + ctx.url;
httpUtil.redirect(ctx.res, url);
};
S3Bucket.prototype.del = function(ctx, next) {
var bucket = this;
this.client.deleteFile(ctx.url, function(err, res) {
if (err) ctx.done(err);
if (res.statusCode !== 200) {
bucket.readStream(res, function(err, message) {
ctx.done(err || message);
});
} else {
ctx.done();
}
});
};
S3Bucket.prototype.readStream = function(stream, fn) {
var buffer = '';
stream.on('data', function(data) {
buffer += data;
}).on('end', function() {
fn(null, buffer);
}).on('error', function(err) {
fn(err);
});
};
inside s3-amazon-aws folder hence I do var s3bucket = require('s3-amazon-aws');
But, now if I have to call the handle function of the module, how do I do that? Also it requires 2 parameters such as ctx,next. How do I get those parameters?
Any help would be appreciated.
The module exports the S3Bucket constructor function. Use it to create a new object. You can then call the handle() method on this object (since it's part of the object's prototype).
var S3Bucket = require('s3-amazon-aws');
var bucket = new S3Bucket(name, options);
bucket.handle(ctx, next)
Regarding the various arguments you need to read the documentation of the library.

Categories