Extract URL from a server in Node.js - javascript

I'm making a Node.js server and I need to extract one part from a URL with this structure:
https://lets-talk-saku-gie-sakura.c9users.io/sala?extract
I just need the extract part.
I need to use the app.get method. However, the only way that I've found is:
app.get('/sala/:id', function (req, res) {
req.params.id;
});
This doesn't work; do you know how can I extract it?

req.params is for URL parameters like :id. Since you want a query parameter you should use req.query instead.
app.get('/sala/:id', function (req, res) {
console.log(req.query);
});

req.query might seem like a way to do this but, unfortunately, it's only useful when you know or expect certain query strings. Your best bet, I think, is to use req.originalUrl and then use a regular expression to find the part of the url you want to extract. See http://expressjs.com/en/4x/api.html#req.originalUrl

The nodejs HTTP doc has an example that can help you:
var obj = require('url').parse(req.url);
console.log(obj.query); // output: extract

Related

Why is URL recognized by Express.js not like the usual URLs that we see?

Why is a URL that is recognizable to Express.js, not like the usual URLs we see?
For example:
Express.js will recognize this URL (http://localhost:3000/things/0) where id=0 if I make this GET request:
app.get('/things/:id', (req, res) => {
// Do somethihng
});
But this URL (http://localhost:3000/things/?id=0) which is more like the usual URLs we see won't work for the same GET request above.
So, "normal URLs" is apparently in the eye of the beholder as there are really just different styles, neither being any more normal than the other.
There are a couple ways to pass parameters in a URL.
#1 - You can embed it in the path of the URL
https://someserver/things/0
https://contacts.google.com/person/c3429579852656514228
This is referred to as a RESTFUL design. These URLs contain a noun and then an id that identifies which of those nouns the URL refers to.
#2 - You can put the variable part of the URL in a query parameter
For those same two URLs above, that could look like this:
https://someserver/things?id=0
https://contacts.google.com/person?id=c3429579852656514228
There are valid reasons for both designs depending upon circumstances and there are even cases where you combine the two (add optional query parameters to the restful API designs in option #1. Neither one is "normal" - they are different ways to design your URLs.
Express allows you to use either one. For restful parameters that are in the path of the URL, you use the :id syntax and you access the value in req.params.id:
app.get('/things/:id', (req, res) => {
console.log(req.params.id);
res.send(req.params.id);
});
For query parameters, you don't define them in the express route path. Instead, Express parses any query parameters that exist on any route and makes them available in req.query.
// expecting /things?id=789&sort=alpha
app.get('/things', (req, res) => {
console.log(req.query.id); // "789"
console.log(req.query.sort); // "alpha"
res.send(req.query.id);
});
Any query parameter that is present in the URL will be added to the req.query object.
Note that query parameters are often considered optional and thus you don't code them into your route definition. If you want to require a specific query parameter, then you have to check if it's there and, if not, then provide some error response or call next() to continue to routing to other request handlers.
FYI, there's another style that often uses client-side code to help build that page and puts URL arguments in a hash tag too, but I'll leave that for another day.
(http://localhost:3000/things/?id=0) which is more like the usual URLs
It's framework and it doesn't do what you and I think. It has set of rules.
Talking about best practices for RESTFUL API, design is that path params(/:id) are used to identify a specific resource or resources, while query parameters(?id) are used to sort/filter those resources. So, for /things/?id=0, We should use query parameters.
we see won't work for the same GET request above.
It will not work that way. In order to get query parameters use something like
app.get('/things', (req, res) => {
let id = req.query.id;
// here you can get id.
});
QUERY PARAMETERS:
How to get GET (query string) variables in Express.js on Node.js?
ABOUT URL: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL

Express Routing Params

I am looking to get this query from this url 'http://localhost:3000/#/quote/edit/?quote_number=1&line_number=1'
from this route in express
router.route('/quote/:quote_number&:line_number')
.get(checkAuthentication, (req, res) => {
let request = new sql.Request(pool)
let get_lines_query = `
select *
from quote_line
where quote_number = ${req.query.quote_number} and
line_number = ${req.query.line_number}`
but it is calling a different query from
route router.route('/quote/:quote_number')
Firstly, the URL you provided doesn't match the route. Your route is to /quote/number&line but your URL is of the form /quote/edit/?quote_number=number&line_number=line.
Secondly, parameters written as ?key=value&key2=value2 are called query parameters, and being special, standard forms of parameters, you don't need to bind them yourself. Express will parse them into the req.query object without you specifying the bindings. So all you need to do is change your route to /quote/edit and you're good.
On an unrelated note, please don't directly stick URL parameters into your SQL query. That's how you end up with SQL injection attacks. Depending on the SQL package you're using, there should be a way to use bound parameters in your queries instead.
Try updating your code to:
router.route('/quote/:quote_number/:line_number').get(function (req, res) {
let quote_numer = req.params.quote_number;
let line_number= req.params.line_number;
res.send(quote_numer + "" + line_number)
})

Express app.get static file with "." in filename

app.get('/images/:filename', (req, res, next) => {
console.log(req.params.filename);
const newUrl = `/static/images/${req.params.filename}`;
req.url = newUrl;
next();
});
Above code works fine if filename does not contain a special character .
For example localhost/images/myImage.jpg will print out myImage.jpg.
If filename contains a . such as localhost/images/my.Image.jpg, console will not print out anything. Is there a way to fix this?
Edit: Added code below. I'm not sure what it does.
app.get(
/^.+\.(jpg|jpeg|gif|png|bmp|ico)$/,
(req, res) => {
res.status(404).end();
}
);
Edit 2: My bad! Like someone's comment, I found the problem was actually from Service Worker. It was apparently messing with caching.
Could somebody explain what ^.+\.$ does in the second piece of code above? I'll mark the answer for that one instead.
I assume it's express.js? If so, :parms is not the best candidate to pass complex values (e.g. something more complex that simple alphaliteral, ehm, params). You could try to pass it to req.query isntead of params and properly escape it client-side and unescape server-side
Please refer to this documentation:
Serving static files in Express

How do I pass a whole URL with http e.g. "http://www.facebook.com" as a parameter to node/express "/:param"?

I can't seem to pass a whole url e.g. "http://example.heroku.com/http://www.facebook.com"
app.get('/:url', function(req, res){
var url = req.params.url;
// do something with url...
}
I always get an error that says "Cannot GET /http://www.facebook.com".
How do I get past this?
Some characters (like /) have special meaning in URLs and need to be encoded.
http://example.heroku.com/http%3A%2F%2Fwww.facebook.com
Most programming languages have a function (possibly via a third party library) which can encode that for you. In JavaScript, for instance, that is encodeURIComponent.
You can use regular expression. For example:
// http://localhost:3000/mountpoint/http://www.facebook.com
app.get( /^\/mountpoint\/(.*)/, function(req, res) {
var url = req.params[0];
res.json(url);
});
Thanks for the comments, answers but I've found out I could use the wildcard and I was able to get the whole URL parameter without running into the 'Cannot GET /' error
'/*'

Using the PUT method with Express.js

I'm trying to implement update functionality to an Express.js app, and I'd like to use a PUT request to send the new data, but I keep getting errors using PUT. From everything I've read, it's just a matter of using app.put, but that isn't working. I've got the following in my routes file:
send = function(req, res) {
req.send(res.locals.content);
};
app.put('/api/:company', function(res,req) {
res.send('this is an update');
}, send);
When I use postman to make a PUT request, I get a "cannot PUT /api/petshop" as an error. I don't understand why I can't PUT, or what's going wrong.
You may be lacking the actual update function. You have the put path returning the result back to the client but missing the part when you tell the database to update the data.
If you're using MongoDB and ExpressJS, you could write something like this :
app.put('/api/:company', function (req, res) {
var company = req.company;
company = _.extend(company, req.body);
company.save(function(err) {
if (err) {
return res.send('/company', {
errors: err.errors,
company: company
});
} else {
res.jsonp(company);
}
})
});
This mean stack project may help you as it covers this CRUD functionality which I just used here swapping their articles for your companies. same same.
Your callback function has the arguments in the wrong order.
Change the order of callback to function(req, res).
Don't use function(res, req).
Also if you want to redirect in put or delete (to get adress), you can't use normal res.redirect('/path'), you should use res.redirect(303, '/path') instead. (source)
If not, you'll get Cannot PUT error.
Have you been checking out your headers information?
Because header should be header['content-type'] = 'application/json'; then only you will get the update object in server side (node-express), otherwise if you have content type plain 'text/htm' like that you will get empty req.body in your node app.

Categories

Resources