I have a script that posts to an endpoint, like so using the node.js request module https://github.com/request/request
const options = {
url: path,
formData: {
name: name,
bundle: fs.createReadStream(path)
}
}
request.post(options, function(err, httpResponse, body) {
if (err) {
console.log('Error!')
} else {
console.log('Success!')
}
})
And I'm trying to catch when the post fails and doesn't work. I tried purposely uploading something and got a 400 response back, but it still came back with success. Is there a more appropriate way to handle error catching with the request module?
The request library doesn't populate the error argument of the request callback unless there is an actual error in the transmission or some other runtime issue. See this issue on the GitHub: 404 error does not cause callback to fail #2196.
Currently request does not handle the HTTP errors. You can wrap the
callback and add your own logic there.
To check for HTTP errors, check the statusCode property of the response argument:
request.post(options, function (err, httpResponse, body) {
if (err || httpResponse.statusCode >= 400) {
return console.error("Something went wrong");
}
console.log('Success!')
});
Related
I am trying to send/update data to mongoDB database via AAJAX call but the command is not reaching theere. I have tried debugging using alert in between the code but the command is not reaching there. Means AJAX call doesn't get executed.
Below is my AJAX POST request code:
var text = "Done";
var data = {
selectedValue: text
}
$ajax({
method: 'POST',
url: '/update-sources',
dataType: 'text/json',
data: data,
success: function(data){
console.log(data);
alert("Working!!")
}
});
And Below is the /update-sources route code:
router.post('/update-sources', function(req, res, next) {
console.log("/Update-Sources")
User.findOneAndUpdate({email: req.user.email}, {$set:{status:data.selectedValue}}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
else
{
res.render('taskswriter');
console.log(doc);
return "Great Working!";
}
});
});
What mistake I am doing?
Would be great if you shared browser's console output, but trying to execute attached client-side snippet, I got the following error:
VM219:7 Uncaught ReferenceError: $ajax is not defined
at <anonymous>:7:1
You've got a typo there - it should be $.ajax as you are accessing a function from within jQuery namespace (https://api.jquery.com/jQuery.ajax/)
Using Heroku, node.js, the npmjs request module, express and php, heroku log is reporting that it can not find a php file.
I am making a GET request from node.js in the index.js server that I made in the Heroku dyno web.1 with this url: "https://chatscroll-code2.herokuapp.com/login2.php" with the hope of receiving some json data back from the php file.
var requestOptions = {
url : "https://chatscroll-code2.herokuapp.com/login2.php",
json : {}
};
request(requestOptions , function(err, resp, body) {
if (err) {
console.log(err);
}
else if (resp.statusCode === 200) {
console.log(body);
} else {
console.log("returned status code="+resp.statusCode);
callback(body);
}
});
The error that I get back from Heroku says that it "Cannot GET /login2.php." The html presented error value from Heroku is contained in the returned body variable.
In the code, body should contain: "{\"result\":"."\"1\",\"reason\":"."\"Successful login\"}";
or
"{\"result\":"."\"0\",\"reason\":"."\"Unsuccessful login\"}";
welcome to StackOverflow !
I think the problem is that you should use the POST method to reach this PHP page. Check in the PHP code which method it is handling.
If it is handling the POST method, your code should look something like this:
var requestOptions = {
method: 'POST',
url: 'https://chatscroll-code2.herokuapp.com/login2.php',
form: {
username: 'something',
password: 'greatpassword' // encrypt with something like PBKDF2
}
}
request(requestOptions, function (err, resp, body) {
if (err) {
console.log(err)
} else if (resp.statusCode === 200) {
console.log(body)
} else {
console.log('returned status code=' + resp.statusCode)
callback(body)
}
})
I have a Discord server where we help each others, don't hesitate joining it :)
I am using node request var request = require(“request”); in my config node to do a POST request and in response get a Cookie which need to be referred in all rest of requests.
I tried enabling COOKIE JAR that works fine if i chain my request under first request but I want to call rest of requests like GetList from custom node.
I tried toughcookie (file cookie) not working when i add var j = request.jar(new FileCookieStore(‘cookies.json’));
node stop working with no error.
Below is my config node, code using which I am getting Cookie.
function myAuthNode(n) {
RED.nodes.createNode(this,n);
this.username=n.username;
this.password=n.password;
this.connect=function(){
//TODO-NG need to make URL configurable
request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("HERE IF I PUT REQUEST Works fine");
console.log("CAN WE PASS ANOTHER REQUEST here from calling SOURCE to execute here?");
});
};
}
Here in this custom node I am calling
// The main node definition - most things happen in here
function GetListNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
console.log('I am called');
//using auth config now you are connected, tell me what is needed?
this.authConfig=RED.nodes.getNode(n.auth);
//connect to config and do auth
this.authConfig.connect();
//THIS ALWAYS FAILS due to cookie not found where as I enable request JAR
request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("Response body:", body);
});
}
Please suggest how to handle cookie in request so that all requests after auth works fine?
Can we pass a request definition to another request for execution inside it or how Cookie can be handled ?
I resolved this by doing below inside GetListNode(), i shifted second request inside the call:
this.authConfig.connect(function(){request.get({url: "http://localhost:8080/api/resource/Project"}, function(err, res, body) {
if(err) {
return console.error(err);
}
console.log("Response body:", body);
});});
and inside config node i did below, added a function parameter and called that passed function, WORKED fine :):
this.connect=function(f){
//TODO-NG need to make URL configurable
request.post({url: "http://localhost:8080/api/method/login", qs: {usr: this.username, pwd: this.password}}, function(err, res, body) {
if(err) {
return console.error(err);
}
f.call();
});
};
I'm having trouble saving a remote zip file to disk with with node.
I'm using request library to make requests. I want to request a zip file,
if the request is succesful write it to disk. I can't get a good combination of
correct error handling and writing the file.
I want to do the following :
request.get('https://example.com/example.zip', {
'auth': { 'bearer': accessToken },
}, function(error, response, body) {
// shortcircuit with notification if unsuccessful request
if (error) { return handleError() }
// I want to save to file only if no errors
// obviously this doesn't work because body is not a stream
// but this is where I want to handle it.
body.pipe(fs.createWriteStream('./output.zip'));
});
I know I can pipe the request directly as follows but I can't get decent error handling. The on error callback doesn't fire for 404s, and if I catch the request and throw an error if !response.ok the empty output file is still written to disk
request.get('https://example.com/example.zip', {
'auth': { 'bearer': accessToken },
})
.on('error', handleError)
.pipe(fs.createWriteStream('./output.zip'));
Instead of using body.pipe(), use response.pipe().
request.get('https://example.com/example.zip', {
auth: {
bearer: accessToken
}
}, (err, res, body) => {
if (res.statusCode !== 200) { // really should check 2xx instead
return handleError();
}
res.pipe(fs.createWriteStream('./output.zip');
});
The downside here though is that the request module is going to buffer the full response. Easy fix... don't use the request module. http.get() is fine and is a drop-in replacement.
Also, I highly recommend checking out the request-promise module which has an option for failing on 404.
I have a branch in a function that isn't currently being tested. It's an error handler coming from a request operation (using the node module of the same name). Here is the particular line:
request(url, function (error, response, body) {
if (error) return cb(error);
Here is the test:
describe("handles errors", function() {
it("from the request", function (done) {
var api = nock('http://football-api.com')
.get('/api/?Action=today&APIKey=' + secrets.APIKey + '&comp_id=1204')
.reply(500);
fixture.getFixture(FixtureMock, function (err, fixture) {
expect(err).to.exist
done();
});
});
Spec fails:
Uncaught AssertionError: expected null to exist
So either sending a 500 status code as a response with no body does not cause an error in the request callback, or I'm testing the wrong thing.
Use replyWithError from doc:
nock('http://www.google.com')
.get('/cat-poems')
.replyWithError('something awful happened');
This variant of #PiotrFryga's answer worked for me, as my request callback(err, resp, body) was actually checking for the "ETIMEDOUT" error code in err:
nock('http://www.google.com')
.get('/cat-poems')
.replyWithError({code: "ETIMEDOUT"});
The only found workaround is to simulate timeout
nock('http://service.com').get('/down').delayConnection(500).reply(200)
unirest.get('http://service.com/down').timeout(100).end(function(err) {
// err = ETIMEDOUT
});
source