I have following in my router get "/flow/reserve/", FlowController, :set_flow_reserved.
when a send a get request to that path, it matches "reserve" to id in path_params in conn. path_params: %{"id" => "reserve"}. and it gives Bad Request error. how to resolve this?
The case you're getting because the order in your router.ex doesn't match the order from action in controller.
Let's say you have routes in this order:
get "/flow/:id", FlowController, :edit
get "/flow/reserve/", FlowController, :set_flow_reserved
so in your controller should be in the same order.
def edit(conn, params)
def set_flow_reserved(conn, params)
When a request is made, all request information from the request path( the route path when sending request) will be sent to controller and it will try to match to the action in controller. So in your case it will match :id to reverse
Related
Here In my mongo collection I have few records. I am writing an API in node js where I pass the ID in request body. My API have to take ID from request body and need to fetch it's whole records in response. but I am getting empty array.
My mongo collection record:
[{ accountId:"a1",name:"test"}]
My Node js code approach:
exports.getById = async (req) =>{
let id = `"` + req.body.accountId +`"`;
let accountId = await db.collection('account-details').find({id}).toArray();
return accountId
}
In request body, I am passing accountId as :
{
"accountId":"a1"
}
The ID is in the form of string. When I am trying to fetch whole records with the provided ID through my API, I am getting response as []. Can anyone please help me on this
You cannot send a body with an HTTP GET, therefore it will not be available in the req object, so req.body.accountId will be undefined and id will be an empty string.
You need to use POST (or PUT) to send body data.
But the more usual solution in your situation is to use GET with dynamic routing, where you add the id to the route e.g.: http://example.com/api/accounts/1234
If you use Express, in your router you need to add the route api/accounts/:id to your router. The id will be available in your code as req.params.id.
See Express docs. For other frameworks this will be something alike.
Hope this helps.
So on my backend server, I have declared a route that accepts params
This is the route:
router.route('/freeze-check/:region').get(freezeCheck);
freezeCheck is just a controller that pulls from the db that filters out products with the regionId.
On my front end I called this route by doing this:
const adminRegion = props.authData.admin.region.id;
const res = await apiCaller.get(`/products/freeze-check`, { params: { region: adminRegion }
apiCaller is just axios exported with some settings. I console logged adminRegion multiple times and it returns the expected value, this is a state pulled from redux store however the backend returns with this:
GET /api/products/freeze-check?region=1 404 30.114 ms - 164
Which I don't get since I declared that route in the backend all the base URLS are working fine I can verify this, am I missing a syntax or something? is this because of the old express or axios version?
I'm using:
express: ^4.14.0
axios: ^0.16.2
By looking at your request response,you're not sending the region as params instead as a query.
GET /api/products/freeze-check?region=1
Try to send the param like this
await apiCaller.get(`/products/freeze-check/${adminRegion}`)
if the params is optional you could to something like this. pass an trailing question mark in a route
router.route('/freeze-check/:region?').get(freezeCheck);
the remaining code should be as it should be.
I have a nestJS gateway, and I need it to proxy a request from my front end to an external API.
I am passing a list of query parameters from the FE.
fe : localhost:3333/autocomplete/prediction?test=2&toto=2
I want my nestJs app to just get the query parameters and send them untouched :
#Get('proxy')
async proxy(#Query() query) {
await this.httpService
.post(`${endpoint}/?${query}`)
}
problemn is, #Query() query return an object and I don't want to reprocess the parameters , and #Req() req: Request doesn't have a simple way to get the string
I just want a good way to retrieve the test=2&toto=2
edit : yes there is req.url.split('?')[1] but isn't there something built in ?
I believe req.search (from http.IncomingMessage) is the way.
I'm trying to implement this example. It looks so simple to implement but I have some troubles.
#Get('test')
async test(
#Query('size', new DefaultValuePipe(10), ParseIntPipe) size: number,
#Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
) {
// Do some stuff
}
The first request I've made is http://localhost/api/test
The requests I sent without params are replied with 400 Bad Request and the message is Validation failed (numeric string is expected).
The second request I've made is http://localhost/api/test?size=&page=
The requests I sent with empty params are passed as 0, not with the value that I want to be provided by default.
In both requests, the default values are expected to pass, right? If so, what am I doing wrong?
I am having a strange problem while writing my api. I am using Nodejs and express. The problem occurs when i try to use GET with parameters.
This is my routes code
router.get('/addFriends/:email', (req, res, next) =>{
const email = req.params.email;
UserSchema.find({email: email}, { "friendsPending.emailSender": 1, _id : 0}, (err, data) =>{
if(err){
res.status(404).send(err);
}else{
res.status(200).send(data[0]);
}
});
});
This is my call in Postman : /users/addFriends?email=a
When running this call, server returns 404 status. It happened even when i tested it with another get call.Any comments are appriciated, however other POST and GET calls work normally (they use body not parameters). Thanks
You mixed query params and url params. To make your example working, you need to use /addFriends/my-email#gmail.com instead of /users/addFriends?email=a.
If you need to send emails via query params (everything after ?) use req.query in your controller instead of req.params.email.
This route definition:
router.get('/addFriends/:email', ...);
expects a URL that looks like this:
/addFriends/someEmail
And, you would use req.params.email to refer to the "someEmail" value in the URL path.
Not what you are trying to use:
/addFriends?email=a
If you want to use a URL such as (a URL with a query parameter):
/addFriends?email=a
Then, you would have a route definition like this:
router.get('/addFriends', ...);
And, then you would refer to req.query.email in the route handler. Query parameters (things after the ? in the URL) come from the req.query object.
In Express, route definitions match the path of the URL, not the query parameters.
when you use /addFriends/:param you force the router to match any request tha have a part in path as :param.For example:
/users/addFriends/toFavorates // will **match**
/users/addFriends/toFavorates?email=a // will **match**
/users/addFriends?email=a // will **not** match
if you want to make :param as optional part of url path put a ? after it
/addFriends/:param?
it will tell express route that :param is an optinal part. See this question
express uses path-to-regexp for matching the route paths. read the documentation for more options