res.json not returning response - javascript

My res.json in my first block of code works, but in the else part of my if statement, it does not. The block that doesnt work, checks for a record in a database then im trying to return the response but im not receiving it.
I've checked and the response is a string, I thought it would have worked as the top part of the code successfully returns the string and it shows in dialogflow (where im trying to return it)
The response is successfully consoled right before the res.json but I do not receive it from the source of the request.
code:
app.post('/webhook/orderinfo', (req, res) => {
const intent = req.body.queryResult.intent.displayName;
const domain = "chatbotdemo.myshopify.com";
const order = req.body.queryResult.parameters["number-sequence"];
if (intent.includes('Order Number')) {
url = "https://test-hchat.com/api/orders/" + domain + "/" + order;
request(url)
.then(function (response) {
order_res = JSON.parse(response)
order_res["fullfillmentText"] = "Hi, Please find your order details below:";
res.json({
"fulfillmentText": JSON.stringify(order_res)
})
})
.catch(function (err) {
console.log(err)
});
// THIS PART DOESNT RETURN THE RESPONSE.
} else {
const domain = 'testStore'
db.getClientsDialog(domain, intent, (response) => {
const fullResponse = response.response
res.json({
fullResponse
})
})
}
});
The database code:
getClientsDialog: function (domain, intent, callback) {
MongoClient.connect('mongodb://efwefewf#wefwef.mlab.com:15799/wefwef', function (err, client) {
if (err) throw err;
var db = client.db('asdsad');
db.collection('dialog').findOne({ domain: domain, intent: intent }, function (err, doc) {
if (!err) {
callback(doc)
} else {
throw err;
callback(err)
}
client.close();
});
console.dir("Called findOne");
});
}
Could it be because this second use of the res.json in the else statement, is trying to call the db first and therefore the link is lost to send the data back?

Related

Vue this.$http.delete() returns 500 internal server only

I'm using axios to connect mysql db with vue frontend, and it's almost done. But the problem is that this.$http.delete() somehow doesn't work at all. I've looked it up but those solutions didn't work. (wrap it {data: book_no}, or {params: book_no}). But it seems like I need to wrap it anyway as an object from vue component when I request(for delete only) the data(req.body.book_no gets undefined data. that's why I added), so I tried few different formats, but it only returns 500 internal server error. Which makes even more 'what?????????' because almost same format of other functions(CRU) are working perfectly.
Please help me out this this.$http.delete method!
Frontend vue component:
btnDelete(book) {
// console.log(book_no);
let book_no = book.book_no;
if (confirm(book_no + " 를 삭제하시겠습니까?")) {
this.$http
.delete("/api/books/delbook", {
book: {
book_no
}
})
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
} else {
return;
}
Backend Books.js delete part
router.delete('/delbook', function (req, res) {
console.log(123)
let bookNo = req.body.book.book_no
console.log(bookNo)
let bookObj = {
'book_no': bookNo
}
console.log(bookObj)
let sql = `DELETE FROM books WHERE book_no = ${bookNo}`
console.log(6666)
db.query(sql, bookObj, function (err, result) {
if (err) throw err;
console.log(err)
console.log(result)
console.log(3234234)
res.send(result)
})
})
error(the only error I've got):
DELETE http://localhost:8080/api/books/delbook 500 (Internal Server Error)

How can I fix set headers in node js?

I am trying to redirect from the condition of a mysql to a get method but it does not work. How could I solve it?
app.post('/responses/',(req,res)=>{
var {text, context ={} } = req.body;
var params = {
input: {text},
workspace_id: '07',
context
}`
`assistant.message(params,(err,response) => {
if(err){
res.status(500).json(err);
}
else {
res.json(response);
console.log(JSON.stringify(response, null, 2));
}
if(response.context.rfc){
var RFC = response.context.rfc;
connection.connect(function(err) {
if (err) throw err;
connection.query(`SELECT * FROM test where RFC = '${RFC}'`, function (err, result, fields) {
if(result.length){
console.log("login");
}
else {
console.log('no login');
res.redirect('/home'); //Her not redirect.
}
});
});
}
});
});
Because show this error: hrow err; // Rethrow non-MySQL errors ^Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
The error message indicates you are trying to set headers after the response is already sent. From your sample code, looks like your API call (whatever assistant.message is) is returning RFC. You then attempt to redirect to another page, but you've already called res.json, which begins sending a response to the browser.
You need to refactor your controller a bit so that you only call res.redirect or res.json, not both.

POST route calls another POST route. Is it possible to get the 'res' of the second POST? express node.js

So I have a POST route that calls a function:
router.route('/generateSeed').post(function(req,res){
generate_seed(res)
});
UPDATE: Here is the genrate_seed() function
function generate_seed(res)
{
var new_seed = lightwallet.keystore.generateRandomSeed();
generate_addresses(new_seed, res);
}
var totalAddresses = 0;
function generate_addresses(seed, res)
{
if(seed == undefined)
{
console.log("seed")
}
var password = Math.random().toString();
lightwallet.keystore.createVault({
password: password,
seedPhrase: seed,
hdPathString: "m/44'/60'/0'/0" //added this changing from Default m/0'/0'/0'/
}, function (err, ks) {
ks.keyFromPassword(password, function (err, pwDerivedKey) {
if(err)
{
}
else
{
ks.generateNewAddress(pwDerivedKey, totalAddresses);
var addresses = ks.getAddresses()
var web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io"));//changed to infura as a provider
var html = "";
var address = addresses;
var seedPhrase = seed;
addToAPI(address,seedPhrase, res); //address
}
});
});
}
function addToAPI(address, seedPhrase, res){
var NewUser = {
publicK: address,
seed: seedPhrase
}
axios.post('http://localhost:3000/CryptoWallet/add/createCryptoWallet', NewUser)//changed from localhost
.then((res)=>{
console.log("Response");
})
.catch(error=>{
console.log(error);
})
}
Which calls to this second route:
router.route('/add/createCryptoWallet').post(function(req,res){
var crypto_wallet = new CryptoWallet(req.body)
console.log("The cyrptoWallet on create", crypto_wallet);
crypto_wallet.save()
.then(crypto_wallet =>{
res.json({data: CryptoWallet({_id:1})}); //<<--- I want this line
})
.catch(err => {
res.status(400).send("unable to save CryptoWallet to databse");
});
});
UPDATE I do get it to POST and save in the database. Right now I can only get the response from the first POST route is there a way to get the response from the second POST route my final goal is the get the _id created by mongo as a response.
Thanks ahead!
You are missing response sending for your first POST request (/generateSeed). addToAPI function need to wait until second POST request is finished and the send its own response. So basically it should look similar to this:
function addToAPI(address, seedPhrase, res){
var NewUser = {
publicK: address,
seed: seedPhrase
}
axios.post('http://localhost:3000/CryptoWallet/add/createCryptoWallet', NewUser)
.then((response)=>{
res.json(response.data); // axios wrappes the body of response into `data` object
})
.catch(error=>{
console.log(error);
res.status(500).('Some error occured');
})
}

Having issues editing an existing DB entry with Sails and Waterline

I'm using SailsJS as an API with Waterline connected to a MongoDB. I'm trying to put together an endpoint to edit existing DB entries but can't seem to get it to work and I'm hitting a wall as to why.
My route:
'post /edit/safety/:id': {
controller: 'SafetyController',
action: 'editSafety'
},
My controller function:
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOneById(id).then((err, safety) => {
if (err) {
res.send(500, err);
return;
}
if (!safety) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
safety.save((err, updatedSafety) => {
if (err) {
re.send(500, err);
return;
}
res.send(200, updatedSafety);
});
});
},
Any push in the right direction would be greatly appreciated.
I don't recognize the Safety.findOneById method - is this something you have custom built? If not, then it is likely your problem.
Try swapping it for either:
Safety.findOne(id)
or
Safety.findOne({id: id})
Note that the returned object will be a model instance if the record exists, and undefined otherwise. If you decide to go with Safety.find instead then the returned value will be an array containing all models matching the query.
Looks like the main issue was transposing the response and err objects. It was successfully completing the query, but loading it into the err object which gets caught and a 500 error is thrown. So I changed that and simplified in a few other places.
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOne(id).then((response, err) => {
var safety = response;
if (err) {
res.send(500, err);
return;
}
if (!response) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
Safety.update({
id: id
}, safety)
.then((result) => {
res.json(200, 'Ok!');
})
.catch((err) => {
sails.log.error('SafetyController.editSafety', err);
})
});
},

nodeJS + MSSQL, connection to db error: undefined is not a function

let's first see the code before I start talking:
var sqlDb = require("mssql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new sqlDb.Connection(settings.dbConfig);
console.log('db.js Send sql-query');
console.log(" ");
conn.connect()
.then(function () {
var req = new sqlDb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log("here it breaks", err);
callback(null, err); //type error: undefined is not a function
})
})
.catch(function (err) {
console.log(err);
callback(null, err);
}); //
};
This function recieves an sql statement and a callback function. When I run the code I get [Type Error: undefined is not a function].
When I comment out the callback(recordset) it doesnt do anything (no error but also nothing else). So I think that the callback is simply not recognized as if it were out of scope. The weird part is, that the error object is transferred back via the same callback function and that seems to work.
The settings.dbConfig looks like this:
exports.dbConfig = {
user: "username",
password: "pwd",
server: "SERVERNAME", // not localhost
database: "DB-Name",
port: 1433
};
I am quite depressed by now. Would someone be so kind as to have a look at my code? I simply don't see the mistake.
Thank you
EDIT:
I call executeSql like this:
var db = require("./db");
var sql = "SELECT * FROM myTable";
db.executeSql(sql, function(data, err) {
if (err) {
console.log(" Internal Error: error connecting Database", err);
} else {
console.log("success", data);
}
});

Categories