i want to make Whatsapp bot and integrated to my website. the system send the qr and users scan it through my website and after users scan and connected i want to send a message to the users it had been connected in the same page. but i got this error
UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
app.get("/create", (req, res) => {
if (req.query["session"] != undefined && req.query["session"] != "") {
venom.create(
`${req.query['session']}`,
(base64Qr, asciiQR, attempts, urlCode) => {
res.send(`<img src="${base64Qr}"></img>`)
},
(statusSession, session) => {
console.log("Status Session: ", statusSession);
},
{ logQR: false, disableWelcome: true
}).then(() => {
res.write("Connected!");
res.end();
})
} else {
res.json({ status: "Error", messages: "Wrong Parameters" });
}
});
res.send() can only be called once. You cannot call this function 2 or more times for a single request.
Related
I'm successfully launching a webauthflow to an social OAuth provider from a service worker background script (as per manifest v3 requirements, background scripts are now full blown service workers)
However I'm unable to send a message back to my content script in what should be the simplest scenario.
Here is my service worker (background.js)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.message === "login") {
if (user_signed_in) {
console.log("already signed in");
} else {
chrome.identity.launchWebAuthFlow({
url: createOAuthEndpoint(),
interactive: true,
}, function (redirect_uri) {
if (chrome.runtime.lastError) {
sendResponse({
message: "fail"
});
} else {
if (redirect_uri.includes("error")) {
sendResponse({
message: "fail"
});
} else {
//we get here but this message is never sent
sendResponse({
message: "success",
profile: "blah"
});
}
}
});
}
}
return true;
});
And here is my content script...(popupsignin.js)
document.querySelector('#sign-in').addEventListener('click', () => {
chrome.runtime.sendMessage({ message: 'login' }, (response) => {
console.log('got the response'); //this log is never written
if (response.message === 'success'){
console.log(response.profile);
}
});
});
Turns out there was nothing wrong with code. There was(is) just nowhere for me to read the console.log(...) output in the callback method for some reason. I added an alert instead and it fired just fine.
I am trying to send back a status of 404 to the web client when a request for a non existent record is received.
I'm using Express and MongoDB. Tested with Advanced Rest Client.
Code:
app.get('/api/courses/:id', (req, res) =>
{
dbo.collection("courses").findOne({ id: parseInt(req.params.id) }, function(err, result) {
console.log(result);
if (err) return res.status(400).send(err);
if (!result) { console.log('Null result sending 404'); return res.status(404); }
res.send(result);
});
});
If the client sends a valid id: then the record is returned as expected.
Node Console:
{ _id: 5d23e6a8c922d263376442c1, id: 1, name: 'Course 1' }
Client:
{
"_id": "5d23e6a8c922d263376442c1",
"id": 1,
"name": "Course 1"
}
When the client sends an invalid id: the console shows the message has been sent but the client waits for ever until I stop/reset the server.
Node Console:
null
Null result sending 404
Because you just set status for the response, but you never send back to client anything.
Let's send something to the client.
Example, send a json object
return res.status(404).json({message: 'Null result sending 404'});
instead of return res.status(404);
I have built an api and i would like to log all of the requests and responses made.
I have a route GET: api/transactions
In this route i return the following response. This wrapper response is quite common throughout my application.
return res.status(200).json({
success: true,
status: 200,
data: transaction,
message: "Successfully retrieved transaction",
});
I have a middleware that is dealing with creating log entries. Inside the res.on("finish") event i want to access the json data i am returning above.
app.use(responseTime((req, res, time) => {
res.on("finish", () => {
// console.log(res);
const responseLog = {
log_id: logId,
line_data_statusCode: res.statusCode,
line_data_statusMessage: res.statusMessage,
line_data_responseTime: time,
message: ".", // get res json message
};
this.log.info({ ...responseLog, ...{ log_type: "response" } });
});
}));
How can i access the res data from the event.
I have a rest API and an app that uses it. The app and postman can both make get requests perfectly. The problem is that on delete requests the app does not work Most of the time but postman works every time. The app also always receives an OK if it works or not. Any help would be appreciated. I am using Node.js and MongoDB for the api and Xamarin for the app
Delete code on server:
// Delete a fish with the specified fishId in the request
exports.delete = (req, res) => {
console.log("Atempting to delete fish with id: " + req.params.fishId)
Fish.findByIdAndRemove(req.params.fishId)
.then(fish => {
if (!fish) {
return res.status(404).send({
message: "Fish not found with id " + req.params.fishId
});
}
if (!Fish.findByID(req.params.fishId)) {
return res.status(200).send({
message: "Fish deleted sucsessfully"
});
}
return res.status(500).send({
message: "Could not delete fish with id " + req.params.fishId
});
}).catch(err => {
if (err.kind === 'ObjectId' || err.name === 'NotFound') {
return res.status(404).send({
message: "Fish not found with id " + req.params.fishId
});
}
return res.status(500).send({
message: "Could not delete fish with id " + req.params.fishId
});
});
};
Just wondering why is this with no callback/.then?
if (!Fish.findByID(req.params.fishId)) {
return res.status(200).send({
message: "Fish deleted sucsessfully"
});
}
Isn't findByID async just like findOneAndRemove?
findByID is async yes, you should handle it that way, or maybe a solution could be to check with ObjectID.isValid() before? Then check for the resolved document would be just enough.
I have a NodeJS Rest API where I have a user collection, besides that I do user SMS verification.
This is the controller for the POST /:id/verification
exports.verification = (req, res) => {
const id = req.params.id
return User.find(id)
.then( user => {
if (user.code !== req.body.code) {
res.json({ message: 'Incorrect code' })
res.sendStatus(500)
return
}
user.isVerified = true
user.save( error => {
if (error) {
res.json({ message: 'Failed to update user' })
res.sendStatus(500)
return
}
res.json({ user })
res.sendStatus(200)
} )
} )
.catch( error => {
res.json({ error })
} )
}
But the thing is that when I post to /:id/verification I get this error
Error: Can't set headers after they are sent. - NodeJS and Express
On this line:
res.json({ user })
res.sendStatus(200)
But I dont understand why, I dont send any response before this.
Can someone explain me what Im doing wrong?
you are using both res.json() and res.sendStatus() both together, both of them send response back, That is why it is showing error that Can't set headers after they are sent.
you should use only one of them.
If you want to send status along with the JSON response, you can try this:
res.status(500).json({ message: 'Incorrect code' });
Also, status of 200 is default when using res.send, res.json, etc. So you dont need to send status 200 with res.json()
res.json() send object to the clilent and after that you are trying to set the header with status code. So, it shows the error message. Use following code for set status and sending the content in the same time.
res.status(500).json({ error: 'message' } /* json object*/);