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
Related
I am trying to send POST request from a NodeJs script to Python server (running with flask and waitress).
Most of the times the request is failed with the below error.
(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up
at connResetException (internal/errors.js:639:14)
at TLSSocket.socketOnEnd (_http_client.js:499:23)
at TLSSocket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:42790) 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:42790) [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 am using NodeJs with axios package to send the request, and the configuration is as given below:
let axiosClient = axios.create({
timeOut: 300000,
maxContentLength: Infinity,
maxBodyLength: Infinity,
httpsAgent: new https.Agent({ keepAlive: true }),
httpAgent: new http.Agent({ keepAlive: true }),
});
let response = await axiosClient.post(end_point_url, data);
And when I checked in the server I could see that the 200 response is being sent, however in the client it is throwing an error.
My expectation is it should be successful in the first try, hence catching the error and retrying may not help in my case as most of the times it fails anyways.
Could you please guide in finding the root cause and fixing the same.
Thank you
let response = await axiosClient.post(end_point_url, data);
You should check end points correctly and use it in try and catch block
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'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" });
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
At https://sebs.github.io/etherscan-api/
is an example how to get a balance.
var api = require('etherscan-api').init('YourApiKey');
var balance = api.account.balance('0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae');
balance.then(function(balanceData){
console.log(balanceData);
});
This works fine.
code:
Server is created and listen on port 8080:
res.writeHead(200, {'Content-Type': 'text/plain'});
balance.then(function(balanceData){
res.write(balanceData);
res.end();
}).catch((error) => {
assert.isNotOk(error,'Promise error');
done();
});
errors:
(node:2388) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: assert is not defined
(node:2388) [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.
What the code has to look like to show the result balanceData at localhost:8080?