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

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...

Related

Express routing giving 404 when receving params

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.

Postman Requests Receive a HTTP 401 Status Code

I am working on creating a Node.js REST API, using the Express module, that redirects HTTP GET and PUT requests to another server. However, when running test queries in Postman, I always get HTTP 401 Unauthorized responses. Yet, when I try the same on query on the Chrome browser I get a successful response (HTTP 302). I read through some documentation on the HTTP request/response cycle and authorization. The server I am redirecting to uses HTTP Basic authentication. In my code I am redirecting the API call to my application server using the res.redirect(server) method. In my Postman request I am setting the username/password in Authorization tab for my request. I know this is gets encoded using base64, but I am guessing this isn't being passed on the redirect when done through Postman.
The following code snippets show what I've created thus far.
This is the Express route I created for GET requests
app.get('/companyrecords/:name', function(req, res) {
var credentials = Buffer.from("username:password").toString('base64');
console.log(req);
var requestURL = helperFunctions.createURL(req);
res.redirect(requestURL);
});
I define a function called createURL inside a file called helperFunctions. The purpose of this function is set up the URL to which requests will be directed to. Here is the code for that function.
module.exports.createURL = function (requestURL) {
var pathname = requestURL._parsedUrl.pathname;
var tablename = pathname.split("/")[1];
var filter = `?&filter=name=\'${requestURL.params.hostname}\'`;
var fullPath = BASE_URL + tablename.concat('/') + filter;
console.log(fullPath);
return fullPath;
}
Where BASE_URL is a constant defined in the following form:
http://hostname:port/path/to/resource/
Is this something I need to change in my code to support redirects through Postman or is there a setting in Postman that I need to change so that my queries can execute successfully.
Unfortunately you can't tell Postman not to do what was arguably the correct thing.
Effectively clients should be removing authorisation headers on a redirect. This is to prevent a man-in-the-middle from sticking a 302 in and collecting all your usernames and passwords on their own server. However, as you've noticed, a lot of clients do not behave perfectly (and have since maintained this behaviour for legacy reasons).
As discussed here however you do have some options:
Allow a secondary way of authorising using a query string: res.redirect(302, 'http://appServer:5001/?auth=auth') however this is not great because query strings are often logged without redacting
Act as a proxy and pipe the authenticated request yourself: http.request(authedRequest).on('response', (response) => response.pipe(res))
Respond with a 200 and the link for your client to then follow.

how to get the landing page URL after redirections using axios

Using NodeJS, If I use axios with maxRedirects = 5, If I type a URL that will be redirected to another URL, how can I get the URL from the final landing page?
In HTTP headers, when there is an HTTP 200 code, there is no header field for the landing page.
Example: if I use:
axios.get('http://stackoverflow.com/',config)
.then(function(response) { console.log(response);}
axios will automatically redirect to https://stackoverflow.com. So, how can get the final URL value "https://stackoverflow.com"?
Should I investigate in the returned object "response" and recreate the full url from domain and URI?
Here is my quick and dirty solution on NodeJS. The starting URL is http://www.stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios , the final landing URL is
https://stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios Please find the trick below to get the landing URL.
axios.get('http://www.stackoverflow.com/questions/47444251/how-to-get-the-landing-page-url-after-redirections-using-axios').then(function(response) {
console.log(response.request.res.responseUrl);
}).catch(function(no200){
console.error("404, 400, and other events");
});
response.request.res.responseURL is the right field in the JSON object that is returned by axios. If you run axios from a browser use console.log(response.request.responseURL);
I solved it by getting it from:
response.request.res.responseUrl
The Nicholas answer failed to get the port (like localhost:8080)
I solved it by getting it from:
response.request.responseURL
The MrFabio's answer failed for me.

Response 302 http url service REST express.js

I have a node system developed in the framework and I express something strange happening with the REST service URL.
For example we had the URL users
GET: / user
With the GET method we returned the user list.
But a few days ago we began sending the error 302, I was researching and refers to a temporary redirect.
if I make the request in this way
GET: / user /
With the diagonal end if I answered 200 ok,
But the weirdest thing if it worked before and all the url of my service I use it without the diagonal end and are working well.
The fastest solution I did is to change the name of the path on the other
example:
GET: / users
but this is not the right solution because other url few days ago we began to fail.
which it is the project
GET: / project
The REST API service is consumed by an angular client.
Data:
I am using the CORS package for crossdomain
//import
var cors = require ( 'cors');
// Apply to all requests
app.use (CORS ());
I hope you can help me find out that should this fail

Nested route in node / express js

I attempting to configure a nested route in Express application like so:
app.put('api/template/:id/page/:pageID', updateTemplatePage);
But when my page makes the call, I get a 404 back. My log shows this:
PUT /api/template/519537192e20b47409c46e72/page/home 404 4ms
home is my page ID in this case, so the call URL looks valid to me. Simpler calls, like GET /api/template/519537192e20b47409c46e72 work just fine. How can I make this work?
I was missing '/' in front of the path. Should be like this:
app.put('/api/template/:id/page/:pageID', updateTemplatePage);
Thank you all for your suggestions.

Resources