Express routing giving 404 when receving params - node.js

I'm working with Express Router, and I'm trying to get some information from params URL, but I cannot make it works as it always returned me a 404.
This is the URL I'm trying to call
http://localhost:8080/api/v1/contr/method?param1=value1&param2=param2
And in my express router I have:
this.router.get("/contr/method", JWT.authenticateJWT, ContrController.method.bind(ContrController));
And I always get
finalhandler default 404 +2m
If I send the request without params the app work as expected:
http://localhost:8080/api/v1/contr/method

If you're building a URL with a URL itself as a parameter, then you need to call encodeURIComponent() on the embedded URL:
let url = "http://localhost:8080/api/v1/contr/method?url=" + encodeURIComponent(otherUrl);
This encodes the parameter in a way that will not be confused with the path of the URL during URL parsing. See doc on encodeURIComponent() for more info.
You need to use encodeURIComponent() on any parameter that contains characters that are special when it comes to URL parsing. They will then be encoded in hex such as %2F which will cause them to not match any of the URL parsing. And, the URL parsing in Express already automatically decodes them for you.

Related

Regex to extract URL domain name with a dash in it using Node.js

I am trying to extract just the websites name from a URL and all the stackoverflow answers haven't led me anywhere.
My URL is in the following format:
https://order-dev.companyname.com
I just want to extract order-dev from the URL.
Got this to work for me (?<=\/\/)(.*?)(?=\.)
If you have an express framework with your node app then it is easy to get a domain/list of subdomains directly from the incoming request..
Using Express Framework
req.hostname() // returns 'example.com'
req.subdomains() // return ['ferrets', 'tobi'] from Host: "tobi.ferrets.example.com"
For plain NodeJS
All Incoming request will contain the following header origin which can be extracted using the following request.headers.origin in any functions where you handle your incoming request MDN LINK
In most JavaScript engines (i.e., most browsers (excluding IE) and Node) you can also use URL for this, specifically URL.host combined with String.prototype.split():
const siteUrl = 'https://order-dev.companyname.com';
const myURLObject = new URL(siteUrl);
const subdomain = myURLObject.host.split(".")[0];
console.log(subdomain); // "order-dev"

How to prevent React-router from messing up your API url

I have a POST endpoint set up like so:
// from server.js
const photo = require('./routes/imagesRoute');
app.use("/api/photo",photo);
//imagesRoute.js
router.route('/photos/:id') // final path will thus be api/photo/photos/:id
.post(employeePhotos)
On the frontend, the component from which the request is made has the following path :
http://localhost:3000/employeePhoto/5fc8a739a89f461274a6286f
I am using axios to POST the request like so:
axios.post(`api/photo/photos/${this.state._id}`,formData )
The challenge is that whenever i make a request to the endpoint 'api/photo/photos' i get a 404 response like so :
POST /employeePhoto/api/photo/photos/5fc8a739a89f461274a6286f 404 22.239 ms - 195
obviously this will not match the endpoint url hence the 404! How would i fix this mix up?
It happens beacause your url in axios is relative, you use this:
axios.post(`api/photo/photos/${this.state._id}`,formData )
I would suggest tu put a "/" before the url:
axios.post(`/api/photo/photos/${this.state._id}`,formData )
When not starting the url with /, it will be relative to whatever your path is currently. I solved the same issue based in this concept, more information
StackOverflow ReactJs...

Node Express sending get request on static file in windows with backslash in path

I see that windows uses \ for path. When same request is issued to backend api it works fine but when issued from axios in frontend, it converts \ to %5C.
what happens differently when request is sent from postman and axios.
At front end:
http://myIp:5000/public\images\ImageName.jpeg
At the back end server:
GET /public%5Cimages%5CImageName.jpeg 401
I am not sure if I correctly understand your question, but may lend you something that helps locate the problem.
In the http uri, the only separator is /. So to GET a static file at static\icon.jpg, you fire a GET request to static/icon.jpg
To explain the %5C nonsense, I recommend to read https://en.wikipedia.org/wiki/Percent-encoding. To put it simple, only few characters are allowed to exist in the uri. To expand the charset used in uri, people invented a code scheme. In this scheme, \ is translated to %5C
Postman has built-in fault tolerance which converts \ to / automatically
For Example:
When I intentionally typed wrong in URL
To Check what Postman send to your back-end: click code button (present under save button)
you can see the corrected URL
Axios is a REST Client which doesn't do anything to correct URL but convert it and make a REST Call.
The main differences is that Postman Corrects the URL before making a REST Call but Axios doesn't.
Looking at the answers above.This worked for me. Simply replace %5C with /
filepath = filepath.replace(/%5C/g, "/");

encode request.query in express

I wrote a simple API to return requset.query in response.
Sample Url:
http://localhost:8082/redirect?requesttype=click&id=79992&redirectto=http://localhost:8081/redirect?name=john&id=123
This returns following response,
but on passing encoded Url things are working as expected(screenshot attached),
http://localhost:8082/redirect?requesttype=click&id=79992&redirectto=http%3A%2F%2Flocalhost%3A8081%2Fredirect%3Fname%3Djohn%26id%3D123
But our API is getting utilized by various customers, is there any method in express.js where I can automatically encode the Url and serve the request as expected.

how to modify server relative url in response

I use http.request a URL and put the response to a new response in Nodejs. But the response of the http request has some server relative url inside, for the links, resources etc.
how can I make the relative url becomes a full url, then I can display the entire content in nodejs response. Thanks.

Resources