Accessing data inside my API with axios post request - reactjs

I'm trying to send an object with my get request so I can use it to retrieve data from the backend like so:
axios.get('/', {
params: {
mainID: usersID.id,
otherID: usersID.otherID
}
});
Now at my API I want to access that params object, how do I do that?
router.get('/', (req, res) => {
//how to access params?
});

You can access the route parameters in Express by req.params
From the documentation:
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
Take a look at the Route Parameters section at: https://expressjs.com/en/guide/routing.html
Hope this helps!

Related

getServerSideProps access current browser url

I am calling getServerSideProps and passing in the req and res parameters like this:
export async function getServerSideProps({ req, res }) {}
I need to get the current browser url path and I can't find it in the request object.
Is there a way to get the current url inside getServerSideProps?
You can use the resolvedUrl field from the context parameter.
export async function getServerSideProps({ req, res, resolvedUrl }) {
console.log(resolvedUrl)
// Remaining code
}
From the getServerSideProps documentation:
resolvedUrl: A normalized version of the request URL that strips the
_next/data prefix for client transitions and includes original query values.
Note that resolvedUrl will not return the domain part of the URL, only the path and query string are returned.

How to retrieve data from URL path with React?

On my server side I'am doing this with express :
app.get('/rooms/:id', function(req, res) {
res.sendFile(path.join(__dirname + '/src/index.html'));
});
This sends an index.html file containing a React component. How can I retrieve the ":id" in the URLfrom within the React component?
Simple answer :
assuming you avoid all other libraries and frameworks, you can simply use the location global variable, you will however need to destruct the query params and map them to your argument (usually located inside location.search).
The complex answer:
Most routing libraries(including React Router) will expose an interface to both describe and map GET variables to named variables.
The url params are located inside the req.params object.
app.get('/rooms/:id', function(req, res) {
let roomId = req.params.id;
res.sendFile(path.join(__dirname + '/src/index.html'));
});

Send URL parameters in Node,Express JS

I have an endpoint https://www..com
When I make a curl call, I have the endpoint as https://www..com?param1=true
I want to do a similar call from Nodejs, I am not sure if param1 should be passed in headers, concatenated to the endpoint or passed in options. What is the right way to do so?
My Node JS looks like this to make calls to my Node Server amd my file looks as follows,
app.post('/thisway', function(req, res){
var ENDPOINT = req.body.endPoint
//(this gets me till https://<url> part of the endpoint string)
var urlToHit = ENDPOINT.concat("?param1=true")
var headers = {
'Authorization': xxxxx,
'Accept': '*/*',
'X-Spark-Service-Instance': xxxxx
}
var options= {
url: urlToHit,
headers: headers,
json: {xxxxxx}
}
request(options, callback);
}
When doing a post it is not necessary to add a query string parameter in the route post. Mostly used for app.get. You can add the details in the JSON string data that you are sending. You can then use the req.body or req.query to get the item. However you can do it this way:
app.post('/thisway/:variable', function(req, res){
Then you retrieve the parameter using req.param.variable
Good EXAMPLE
You can pass it as you have shown in your example in urlToHit. You don't have to pass it in header or options.
var urlToHit = ENDPOINT.concat("?param1=true")
This should complete the request with the needed parameters. Since even when you are doing a curl call, this is the endpoint you hit, it should be the same endpoint here as well.
In your angularjs make a post request to /thisway?variable=true rather than /thisway and in your router you can configure as following:
app.post('/thisway', function(req, res){
var variable = req.query.variable;
if (variable) {
//do something
} else {
//do something
}
});

React-router server side match translated routes?

I'm using react-router for server side rendering and I have locale information stored in a locales.json file. The locale information is only set after a response from an api call, which includes the current language, i.e. 'GB', 'NO', 'FR', etc., which then completes the server response and everything is fired through to the client in the correct language.
However, I'm using the react-router match method:
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { ... }
...and I need the routes to be based off the language from the api response, i.e.
// Route
<Route path={`:storeId/${locales[language].path}`} />
// locale.json
{
"GB": {
"path": "contact"
},
"NO": {
"path": "kontakt"
}
}
Is this approach possible? It's like I need to define routes after the api call is made, but to make the api call, I need routes defined.
Yes, I haven't tried your example specifically, but it is definitly possible to define routes from an api response and pass it to the "match" function.
You could try something as following:
function handleServerRendering(req, res) {
axios.get('http://localhost:3001/myCutomeRoutes')
.then(function(response){
const myRoutes = {
routes: response.data,
location: req.url
}
match(myRoutes, function(error, redirectLocation, routeContext) {
// WRITE YOUR CODE IN HERE...
})
})
.catch(function(err){
console.log('error', err);
})
}
As you can see, you firstly do an API call and then you pass the response.data to routes inside "myRoutes" constant

Passing two parameters to Express Mongoose api to return single result

I'm new to creating APIs with Express and Mongoose.
I've been able to setup my basic endpoints, get, post, put, etc.
But now I want to set one up where I pass two parameters to search a collection and return a single result.
I don't think I'm passing the parameters correctly.
In my angular, I have the following service call, which I know is correct:
.factory('LoginFactory', function($resource){
return $resource('/api/user?email=:eml&password=:pwd', {}, {
query:{ method:'GET', isArray:true, params:{ eml:'#eml', pwd:'#pwd'}}
});
});
But I don't think I'm doing it right in my express/mongoose API. Here is my endpoint:
router.route('/:email:password')
.get(function(req, res){
User.findOne({email:req.param.email, password:req.param.password}, function(err, user){
if(err)
res.send(err);
res.json(user);
});
});
I use req.params not req.param
and I have a slash before each param
app.get("/:email/:password", function(req, res){
console.log(req.params.email)
console.log(req.params.password)
})
req.params
This property is an object containing properties mapped to the named
route “parameters”. For example, if you have the route /user/:name,
then the “name” property is available as req.params.name. This object
defaults to {}.
You just have one paramater that looks like this :email:password. You got to add a slash to create a URL segment so that express can recognize it as a route paramater.

Resources