request.get() - if url not found - node.js

So I want to end the request if the user tries to fetch a url which does not work.
This works:
var remote = "https://storage.googleapis.com/ad-system/testfolder/OUTOFAREA.mp3";
var streama = request.get(remote);
however lets say the following mp3 does not exisit
https://storage.googleapis.com/ad-system/testfolder/playme.mp3
When the request.get('https://storage.googleapis.com/ad-system/testfolder/playme.mp3'); tries and fetch the file it will return a 404 error. What I want to do is file not found I want to run res.end();
Any ideas?

you can write like ### request('endpoint url goes here', { json: true }, (err, res, body) => {
if (err) { // keep your business logic here}
}) ######
hope it helps

I doesn't know about this Cloud Storage but even the link isn't accessible so I recommend you check if something is wrong in this service or if you require some special keys or something else to access the content or the service. Then, check your code or use a library that can handle your requirements (if available).
If I found something, I'll let you know :)
EDIT: I can access to https://storage.googleapis.com/ad-system/testfolder/Video/30%20Second%20Timer-0yZcDeVsj_Y.f137.mp4

You could do
app.get("*",(req,res)=> {
res.end()
});
and insert it just before your 404 handler however, I would challenge why that ever might be a good idea. If it's literally so you scan skip checking the return code I really advice you to think twice if thats something you wanna be doing atleast do:
app.get("*",(req,res)=> {
res.status(404)
res.end()
});

Related

Axios in node.js check url before executing code

I dont find anything that works for me so I ask here:
I am trying to get some data from a website with axios. It works great, but if I input the wrong URL I get an error. I want to check if the URL with its complete path to the page I desire exists.
I tried npm package url-exists but it just said the path didn't exist eventho it did.
Is there a simple way to check if a path like for example "https://github.com/enterprise" exists or if it doesn't?
You have to make a request anyway to check if the url exists. So you can handle it when you got 404 status code in catch error block of axios function.
The only way is making the request, you can handle this scenario using a try/catch block
const getSomething = async () => {
try {
const something = await axios.get("www.website.fake")
} catch (err) {
throw new Error(err)
}
}

how to pass data and redirect in express

My code is
main.post('/userlist', function(req, res, next) {
// where did you get this?
// var db = req.db;
var query = connection.query("SELECT name,zaman,giriscikis FROM giriscikis where date_format(zaman,'%Y-%m-%d') between ? and ?", [req.body.bas, req.body.bitis], function(err, result) {
if (err) throw err;
console.log(result);
res.send(httpResponse(result));
return res.redirect('/zamansorgu');
//console.log(req.body.bas)
//console.log(req.body.bitis)
});
});
I want to fecth data from database and redirect to same page in the code(zamansorgu.html)
But I get an error
Cannot set headers after they are sent to the client
How can I solve this problem
thank you for your helps
You are attempting to send back JSON data and redirect to a different page. That's not possible. Each endpoint request can have one response, not more. You can either send back the data, or redirect. That's because redirecting really does send back data too (the html of the new target page).
Think about it from the caller's point of view. If it did allow this how would it work? If someone uses this link from a browser should the browser show the JSON data you returned, or should it take the user to the new page?
The error is saying "hey, I already sent back data. I can't redirect now because we are already down the path of returning some JSON".
If you want to use the data to format the output that can be done, or if you want to redirect to a new location and pass the data in the url, that's also possible. Consider code like this:
main.post('/userlist', function(req, res, next) {
// var db = req.db;
var query = connection.query("SELECT name,zaman,giriscikis FROM giriscikis where date_format(zaman,'%Y-%m-%d') between ? and ?", [req.body.bas, req.body.bitis], function(err, result) {
if (err) return next(err);
if (result.urlparam) {
// this builds a new url using the query value
const nextUrl = `/zamansorgu?param=${result.urlparam}`;
return res.redirect(nextUrl);
}
else {
// this builds html here
const html = `<html><body><h1>${result.title}</h1></body></html>`;
return res.send(html);
}
});
});
I also ran into this, in my case it was quite a deceptive little bug. A node-inspector session helped me pinpoint the problem quickly however. The problem in my case was pretty bone-headed, the res.end call in the sample below is the offending line.
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(someObject));
someObject did not exist after a refactor and that was causing a ReferenceError to get thrown. There is a try-catch in Router.prototype._dispatch that is catching the ReferenceError and passing it into next
res.status(301).redirect(`/zamansorgu?name=${"John"}&email=${"john#email.com"}`)
So, this is something I explored but it will be dependent on the structure of your application. You could always pull the data out using query params and hydrate your application.

Retrieve ms-rest-azure authentication code with interactiveLogin method

I'm trying to push one inputless TV screen dashboard (using chromecast) with azure authentication in nodejs (working fine without auth so far)
My best move (?) is using ms-rest-azure package allowing to perform initial authentication from another device with https://aka.ms/devicelogin & a code
However, is there a clean way to retrieve this code and make it available outside the console ? I can't find reference or callback.
My fallback scenario would be to intercept process.stdout.write but feels like dirty.
There is an options object you can pass to interactiveLogin. One option is "userCodeResponseLogger", which should be a function, eg
let options = {"userCodeResponseLogger":(msg)=>{
console.log("I have the message",msg)
}
}
msRestAzure.interactiveLogin(options).then((credentials) => {
// doing authentication stuff
});
Note you'll still need to parse the msg to extract the code.
had to go forward on this issue and finally ends up by intercepting process.stdout.write with a better implementation then mine : https://gist.github.com/pguillory/729616/32aa9dd5b5881f6f2719db835424a7cb96dfdfd6
function auth() {
hook_stdout(function(std) {
var matches = / the code (.*) to /.exec(std);
if(matches !== null && matches.length >=2) {
var code = matches[1];
// doing something with the code
unhook();
}
});
msRestAzure.interactiveLogin().then((credentials) => {
// doing authentication stuff
});
}

node.js - how to modiffy response headers

Platform: node.js + express and request modules (beginner).
HI, I got simply router.get followed by a request and I want to modify the headers it get from external server, and send it to the user that requested the specific data.
router.get('/', function(req, res){
var someUserRequest = request('http://google.com', function(error, resp, body){
if (error){
console.log(error);
}
console.log(resp.headers); //lets assume that there is 'x-content-type-options' that I don't want for example
}
req.pipe(someUserRequest).on('response', function(response){
delete response.headers['x-content-type-options'];
console.log(response.headers); // everything looks fine here - no 'x-content-type-options'
}).pipe(res);
});
module.exports = router;
So it seams that there is no 'x-content-type-options'. However when I check this out in chrome developer tools (network) I can clearly see 'x-content-type-options: nosniff' - even when I clear all history/cache.
So why it's not working? Can somebody explain me where is the error?
I think that you might need to splice the array instead, try putting a test condition before and after you
delete
to see if
['x-content-type-options']
exists in response.headers.
If it does then you can probably splice instead.
Read more on delete here

How to get Express to return the object I just deleted in MongoDB

Feel free to let me know if this isn't a common practice - I'm a fairly new programmer - but I thought I've seen APIs in the past that, when you submit a DELETE request to a resource (/todo/1234), some servers will return the object you just deleted in the response. Is that a thing? If so, I'd be interested in learning how to do it. Here's what I have:
.delete(function (req, res) {
Todo.findById(req.params.todoId).remove(function (err) {
if (err) res.status(500).send(err);
res.send("Todo item successfully deleted");
});
});
This code does delete the item, but I would like to return the item that got deleted in the response instead of a string message. If that's a normal/okay thing to do. If it isn't normal or okay for some reason, please let me know why and I'll just move on. Or perhaps there's a more common way.
This is what I found in the [RFC 7231 docs][1]:
If a DELETE method is successfully applied, the origin server SHOULD
send a 202 (Accepted) status code if the action will likely succeed
but has not yet been enacted, a 204 (No Content) status code if the
action has been enacted and no further information is to be supplied,
or a 200 (OK) status code if the action has been enacted and the
response message includes a representation describing the status.
I'm having a hard time interpreting what the 200 response means - is it only kosher to send a string message (Success!) or an object containing a message attribute ({message: "Success!"})? Or can you do whatever you want there? What's the best practice in Express using Mongoose?
Thanks in advance for the help, and sorry for my noobness with HTTP stuff.
[1]: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5
You should use findOneAndRemove! Something like:
Todo.findOneAndremove({ id: req.params.todoId }, function( error, doc, result) {
// it will be already removed, but doc is what you need:
if (err) res.status(500).send(err);
res.send(doc.id);
});

Resources