I'm writing a simple voting web api for a class. I'm currently working on PUT and my code is working, but I'm getting a strange error in my command line terminal. Here is the code I'm using to call PUT:
async addVotes(item) {
try {
let response = await axios.put("/api/candidates/" + item._id);
this.getItems();
return true;
}
catch (error) {
console.log(error);
}
console.log(item.name + " is checked");
},
async submitVotes(items) {
for (var item of this.items) {
if (item.selected) {
this.addVotes(item);
}
else {
console.log(item.name + " is not checked");
}
}
},
and here is the PUT code for the api:
app.put('/api/candidates/:id', async(req, res) => {
console.log("initiated put(edit) request");
try {
let candidate = await Candidate.findOne({ _id: req.params.id });
candidate.numVotes += 1;
candidate.save();
res.send(candidate);
res.sendStatus(200);
}
catch (error) {
console.log(error);
res.sendStatus(500);
}
});
I'm getting an error saying this:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:102:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:106:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13246) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
From what I've researched online I'm getting this error because I'm getting more than one response, but I am using async/await so I don't understand why I should be getting that error.
The way you add status to the response is incorrect.
Instead of
res.send(candidate);
res.sendStatus(200);
You should do it this way
res.status(200).send(candidate)
sendStatus sends an 'OK' message on top of setting the status code. You may refer to the Express API reference here https://expressjs.com/en/api.html
The problem is with your PUT API implementation in which you're sending the response twice:
res.send(candidate); // sending json response back to client
res.sendStatus(200); // trying to send response status
So if you're sending a json response then you do not need to send response status explicitly.
res.send(candidate); OR res.json(candidate);
However, if you want to specify the response status then you can do chaining like:
res.status(500).send({ error: "boo" });
Related
i have implemented a very minimalistic backend service using expressjs and socket.io to transfer serial data readings from an arduino to a react front end. i use SerialPort package to achieve this. my problem is when i try to connect to serial port that is not available or not connected the SerialPort library throws out following error.
(node:940) UnhandledPromiseRejectionWarning: Error: Opening COM6: File not found
(Use `node --trace-warnings ...` to show where the warning was created)
(node:940) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
this error is completely acceptable and expected because i'm trying to connect to a device that is not exists. but i want to handle this error nicely and notify the fronted that the serial port connection is failed. to achieve this i used a try catch block like following.
io.on("connection", function (socket) {
socket.on("start", function () {
console.log("Device connection starting...");
try {
port = new SerialPort("COM6", { baudRate: 9600 });
parser = port.pipe(new Readline({ delimiter: "\n" }));
} catch (error) {
console.log(error);
io.emit("error", "Can't Connect!");
console.log("error msg sent");
}
});
});
but when the error is thrown this catch block will not run. what can i do to fix this issue ? how can i handle this error ?
Instead of a try-catch-block, use the error event:
port = new SerialPort("COM6", { baudRate: 9600 })
.on("error", function(error) {
console.log(error);
io.emit("error", "Can't Connect!");
console.log("error msg sent");
});
parser = port.pipe(new Readline({ delimiter: "\n" }));
Hi I'm new in javascript, I try to post url-encoded Api from lala.ai. I,m followed the instructions from the internet but still got an error. below I put the code and results.
//This is the instruction
POST /api/preview/
Puts a file in the preview queue (the first minute of vocals).
Parameters (form-urlencoded):
id (str): File id obtained from /upload/ method.
filter_type (int, optional): Number of postprocess iterations with MWF.
webpush-callback (json, optional): Client data for sending push notifications.
Returns (json):
{
"status": "success" | "error"
"error": Error description if the status is "error"
}
Examples:
$ curl --url https://www.lalal.ai/api/preview/ --form-string "id=9a3ae258-7693-4046-87c2-ef577eb752bb" --form-string "filter_type=2"
{"status": "success"}
$ curl --url https://www.lalal.ai/api/preview/
{"status": "error", "error": "No file id"}
This is what I have tried
const qs = require("qs");
axios
.post(
"https://www.lalal.ai/api/preview/",
{
data: qs.stringify({
id: "4d2f9262-e578-4290-97d3-43303fffbf56",
filter_type: "2",
}),
},
{
headers: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8",
},
}
)
.then((result) => {
console.log(result);
});
This the error result I got
(node:34480) UnhandledPromiseRejectionWarning: Error: Request failed with status code 403
at createError (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (D:\reactjs\upload_lalal\server\node_modules\axios\lib\adapters\http.js:244:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:34480) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:34480) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Can someone explain to me why that is error and how to fix it? Thanks.
Your error is... HTTP 403, which means
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden
Do you need an access token to use the API?
I wrote this twitter weather bot, which worked fine since last month, but an hour ago it crashed and I can't seem to bring it back up.
Can anyone simply explain me what it is and also what the error is, when it arises and what I have to check to get rid of this warning?
I did search up how to fix an "unhandled promise rejection" but could not find out what it is.
const Twit = require('twit');
const config = require('./config');
const rp = require('request-promise-native');
async function setup(location) {
const options = {
url: "http://api.apixu.com/v1/current.json",
qs: {
key: API_KEY,
q: location
},
json: true
};
let result = await rp(options);
let condition = result.current.condition.text;
let tweetText = `The condition in ${location} is currently ${condition}, and the temperature is ${result.current.temp_c}°C.`;
console.log(tweetText);
sendTweet(tweetText)
}
function sendTweet(text) {
const T = new Twit(config);
var r = Math.floor(Math.random()*1000);
const tweet = {
status: '[' + r + '] ' + text
}
T.post('statuses/update', tweet);
}
setup('Colombo');
2019-08-21T06:41:52.820595+00:00 app[scheduler.8141]: at setup (/app/bot.js:25:36)
2019-08-21T06:41:52.820597+00:00 app[scheduler.8141]: at process._tickCallback (internal/process/next_tick.js:68:7)
2019-08-21T06:41:52.820719+00:00 app[scheduler.8141]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
2019-08-21T06:41:52.820834+00:00 app[scheduler.8141]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2019-08-21T06:41:52.903455+00:00 heroku[scheduler.8141]: State changed from up to complete
2019-08-21T06:41:52.880762+00:00 heroku[scheduler.8141]: Process exited with status 0```
When you call the api with:
let result = await rp(options);
You are setting result as a promise to wait for the API call, but your request is not accepted for some reason and then you are getting a promise rejection but not handling.
Please use:
await rp(options).catch(err => console.log(err))
So you can log your error, then we can investigate your error.
---------- EDIT ------------
Just tested it myself, and we are getting a 503 HTTP Status code:
Here is the log print
It means that the service is not available, not receiving requests.
---------- EDIT -----------
It is working again, tried here, I'm getting 200 HTTP Status code and a good response, now you should be good to go
I'm running a small HTTP server on an RPI3B. It logs every request made, so in Postman, I can make a request to the server and it is received, logged and returns the correct value. However, using this function:
function get(action, path, content) {
return new Promise(function(resolve, reject) {
let body = "";
let req = http.request({
host: "10.0.0.12",
method: content ? "post" : "get",
path: `${action}?path=${path}`,
headers: {
token
}
}, res => {
res.on('data', data => {
body += data;
})
res.on("end", e => {
resolve(body.toString());
})
});
req.end(content);
req.on("error", e => {
reject(e);
})
});
}
I get the following error:
(node:24956) UnhandledPromiseRejectionWarning: Error: socket hang up
at createHangUpError (_http_client.js:313:15)
at Socket.socketOnEnd (_http_client.js:416:23)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1081:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:24956) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an asyn
c function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:24956) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not
handled will terminate the Node.js process with a non-zero exit code.
I have looked at common symptoms of this error and noted that I receive the error immediately after the request is sent (as opposed to when the request times out). I also noted that I have the req.end() method called to ensure the request is ended, but the result remains the same.
Any insight as to how this might be caused and how it might be resolvable would be greatly appreciated.
Note Both sides are written in Node.JS
so I'm trying to catch UnhandledPromiseRejectionWarning in my promise, but for some reason it's not working. It ignores my code and just outputs the error to console.
Error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): Error: Forbidden (Cannot send messages to this
user)
code:
e.message.author.openDM().then((message) => {
message.sendMessage(`test`);
}).catch((error) => {
e.message.channel.sendMessage(error + "test");
});
This is a discord bot, using discordie. In my mind, the above code should send the word "test" to a messages author via private message, if the bot can't, it will send the error and the word test in the channel they sent their message in. However, the second part (inside the catch) doesn't get executed.
tl;dr, The catch in the above code isn't working and I'm getting the above error in console instead if the bot doesn't have permission to dm the user.
You forgot the return statement inside the then function.
I suppose message.sendMessage('test') returns a promise
e.message.author.openDM().then((message) => {
return message.sendMessage(`test`);
}).catch((error) => {
e.message.channel.sendMessage(error + "test");
});