Query String missing when redirecting with expressjs - node.js

I have the following express js route which helps in redirecting to the given URL.
app.get("/", async (req, res) => {
const url = req.query.url;
res.redirect(url);
});
It's working fine. But the problem is, somehow the passed query strings is getting cut off for no reason.
Example:
This is what I'm actually passing.
http://localhost:3000/?url=https://google.com/?abc=123&def=456&aaa=098
After redirecting whatever after the first query string goes missing.
It's appearing like this.
https://google.com/?abc=123
Not sure why &def=456&aaa=098 goes missing.

Use the encodeURIComponent and decodeURIComponent functions.
For example:
app.get("/", async (req, res) => {
const url = req.query.url;
res.redirect(decodeURIComponent(url));
});
Note that the url parameter must be encoded in the actual URL.
Your URL should look something like this:
http://localhost:3000/?url=https://google.com/%3Fabc%3D123%26def%3D456%26aaa%3D098

Related

first portion of route url is not included

I have a route where I built two GET APIs. I would like one to redirect from /download to /zip all while passing a parameter. The problem is I am getting a 404 for some reason the routes url is not being included in the redirect()
Here are the APIs.
// respond with xml from from static folder
router.get('/zip/:id', function (req, res) {
fileName = req.params.id
});
router.get('/download', function (req, res, next) {
var id = req.query.id
res.redirect('/zip?id='+ id);
});
module.exports = router;
I get a 404 when testing the URL:
localhost:8000/rest/pluto/v1/plugin/download?id=networktool
I am thinking it might be how I have the middleware setup but not real sure. I'm still new to node/express.
You are redirecting to a route that isn't actually defined. With your /zip/:id route definition:
router.get('/zip/:id', function (req, res) {
var fileName = req.params.id
});
The way that is defined, you have to have id information in the URL itself, so while the following routes would work:
/zip/networktool
/zip/1234
these routes would not:
/zip
/zip?id=networktool
/zip?id=1234
because Express is looking for the id to be built into the route itself. So you can do one of two things. You can either change your redirect to:
router.get('/download', function (req, res, next) {
res.redirect('/zip/'+ req.query.id);
});
or, you can modify your /zip route to make the id parameter optional with ?:
router.get('/zip/:id?', function (req, res) {
var fileName = (req.params.id) ? req.params.id : req.query.id;
});
I would recommend the first option, as the latter optional parameter only makes your zip route more complicated and require extra handling of whether id is actually passed to your route.
The path /zip/:id is expecting a path parameter not a query parameter.
You should redirect like this
res.redirect('/zip/'+ id);

How to get the router values containing special characters in express router

I am working on to get route value in Nodes js using express framework
the url goes like
http://localhost:3000/course/view/turbine/turcV39/%20V42/%20V44/%20V47
Need to get the value "V39/%20V42/%20V44/%20V47" from the above url and route
router.get('/view/turbine/:turc?', function(req, res) {
console.log('a');
});
You can use regex to get it, like this
app.get(/\/view\/turbine\/turc(.*)/, function(req, res) {
console.log(req.params[0])
});

Resolve URL with info from URL parameters

I've been thrown at a Node.js project at work and I'm not a Node developer. My first task is to resolve urls to stores from a URL parameter. Here's what needs to happen:
The original URL contains the URL parameter "siteName" as here:
https://example.com/s/Store/?siteName=SLUG
The above url with parameter would then resolve to
https://example.com/s/Store/SLUG
This project is running on Express ^4.3.0.
I've been diving into the Node docs but I'm not sure even where to start.
I would suggest you look into Express
The solution to your problem is easy. Firstly, you'd need to establish a middleware to listen to requests for /s/Stores route. Then parse the query params and get the value for the siteName key. Finally use the res.redirect method to run the logic for /s/Store/SLUG route.
The solution would look something like
app.get('/s/Stores', (req, res, next) => {
const query = req.query;
const siteName = query.siteName;
res.redirect('/s/Stores/' + siteName);
});
app.get('/s/Stores/:siteName', (req, res, next) => {
const siteName = req.params.siteName;
if (siteName === 'SLUG') {
// do something
}
// do something else
});
Assuming Store route is the page you want to see with parameters, if you are using url query parameters, use first example and it matches your first question.
If you are trying to get url parameters without query, use second example.
//https://example.com/s/Store/?siteName=SLUG
app.get('/Store', function(req, res){
let siteName = req.query.siteName,
});
//https://example.com/s/Store/SLUG/
app.get('/Store/:slug', function (req, res) {
let slug = req.params.slug,
});

req.query undefined in Nuxt Express Middleware get request

Not a pro with things like server middleware, but stuck without much clues.
In a vue component I am retrieving data with axios with this:
axios
.get('/api/getDailyFeedback', {
params: {
start: '2018-05-01'
}
})
Which goes to the express (version 4.16.2) server middleware setup in Nuxt. I have gotten normal get and post requests to work fine but the problem is when I want to pass in a parameter into a get request like the below:
router.get('/getDailyFeedback', (req, res) => {
console.log('Query:', req.query.start);
//do stuff
});
What little experience I had with Express 4, it took me a little bit of time to realise why parameters passed in the body of a post request were undefined, but it was because I needed to add body-parser.json() to my nuxt config since they removed that from the main express package. Similarly I thought I needed bodyParse.urlencoded but that has not worked. This is the line I added to my nuxt.config:
serverMiddleware: [bodyParser.urlencoded({ extended: false }), bodyParser.json(), '~/api'],
I am unsure if the content type is not set correctly or I am missing something simple here. I know I am able to use various libraries to grab the parameters from the url string which I have access to, as Axios is working as expected and adding my 'params' object onto the end of my get request. But a lot of solutions I have seen to other problems is 'oh its as simple as accessing req.query' Alas Express fails to define a req.query object, or even req.params or req.body.
Hopefully that is enough detail to go on, thanks a lot for reading and any suggestions.
Well that's an unpleasant surprise to try to use the get request in Nuxt for the first time, isn't it? Nuxt creates a connect instance which leads to some pitfalls. It's req is the Node.js http request object, so it doesn't have the query property and request.body is also being skipped in get requests!
But there is a way for everything. Your code:
axios.get('/api/getDailyFeedback', {
params: {
start: '2018-05-01'
}
})
Translates to the following URI call:
/api/getDailyFeedback?start=2018-05-01
So you've got all the params in the URI where you can retrieve them from via url parsing. Module url ships with Node.js by the way.
const url = require("url");
router.get('/getDailyFeedback', (req, res) => {
let queryData = url.parse(req.url, true).query
console.log('Query:', queryData.start)
});
I wrote a little helper that extends req with a custom property. Here's the code:
router.use((req, res, next) => {
var theQuery = url.parse(req.url, true).query
req.queryData = theQuery
next()
})
Then you can use it like this:
router.get('/getDailyFeedback', (req, res) => {
console.log('Query:', req.queryData.start)
});
Other way to pass params via get is by using optional uri segments:
router.get('/getDailyFeedback/:start?', (req, res) => {
console.log('Query:', req.params.start)
});
I am using Nuxt 2.15 and I can access the query parameter like this req._parsedOriginalUrl.query
You can access Nuxt get params without additional modules.
Just use:
req.request.get()
For anyone else in the future
const { Router } = require('express')
Router.get('/orders', async (req, res, next) => {
const request = req.query.sometext;
res.json({data: request});
});
module.exports = Router;
<script>
export default() {
async mounted() {
const orders = await axios.get(`/api/orders`, {
params: {
sometext: 'bla bla'
}
});
}
}
</script>
http://expressjs.com/en/api.html#req

URL as parameter in Express

Using Node.js with Express, how do I accept a URL as a parameter?
i.e http://example.com/site/http%3A%2F%2Fgoogle.com
I have the following handler
app.get('/site/:dest', function (req, res, next) {
res.end('URL = ' + req.params.dest);
});
Rather than getting the expected response i get a 404:
The requested URL /site/http://www.google.com was not found on this
server.
If i request example.com/site/hello it works fine, but not for passing a URL. I assume its the forward slashes escaping that's causing the problem.
Is there a correct way to do this?
It's worked for me
app.get('/site/*', function (req, res, next) {
res.end('URL = ' + req.params[0]);
});
You need to encode your parameter's URL. You will have a lot of issues if you just send the URL as a param.
Best way is to url encode the param and on your nodejs side you will need to url decode
Example:
https://www.google.com will be https%3A%2F%2Fwww.google.com
Here is a workaround:
Changed the routing and now using req.query
app.get('/', function (req, res, next) {
res.end('URL = ' + req.query['site']);
});
Now, http://example.com/?site=http%3A%2F%2Fexample.com%2F%3Fhello%3Dworld%26foo%3Dbar works as expected.

Resources