Can't get url Parameter inside controllerFunction node js - javascript

In my index.js I have given routing in such a manner.
app.use('/users/:id/transactions',transactionRoutes)
Inside transactionRoutes
router.get('/:txnHash',transactionController.getTransaction);
so request to '/users/:id/transactions/:txnHash' will come to the above route.
Inside transactionController
module.exports.getTransaction = (req,res) => {
let typeOfTransaction = req.query.type,
userId = req.params.id,
txnHash = req.params.txnHash;
}
Here I am able to access the txnHash parameter but the userId parameter shows undefined. I think it is because the :id part of the route is specified in the index.js. Is there any method to solve this problem without changing the routes.
API Request is
GET 'apiurl/users/42342234/transactions/234bh2428b354hjcs'

In your TransactionRoutes you need to add mergeParams which will preserve the req.params values.
var router = express.Router({mergeParams: true});
Before your,
router.get('/:txnHash',transactionController.getTransaction);
Hope this helps!

Related

Not able to use query param with expressJs api in localhost

In my index.js file
app.use('/api/v1/users', userRouter)
In Router file
router.get("/:id", getUserDataById);
In postman:
My GET URL looks like this: http://localhost:3000/api/v1/users?id=120622
Error it gives:
Cannot GET /api/v1/users
I think, this is how query param should be given according to the docs and tutorials i followed, but this error won't go away.
If i remove query, then other endpoints work perfectly.
I am not able to catch what's going wrong here.
I am stuck with this from last 2 days.
Just a hint to resolve this, will help me a lot.
Thanks in advance!
Firstly your index.js and routes.js file is fine now you just need to send request correctly see the req.params is different and the req.query is different
First Way with (Query)
In postman:
http://localhost:3000/api/v1/users?id=120622
Your Index.
app.use('/api/v1/users', userRouter);
In Router file.
router.get("/", getUserDataById);
How did you get that id;
let id = req.query.id;
Second Way with (Params) - Look at the postman URL carefully and at Route
In postman:
http://localhost:3000/api/v1/users/120622
Your Index.
app.use('/api/v1/users', userRouter);
In Router file.
router.get("/:id", getUserDataById);
How did you get that id;
let id = req.params.id;
This is the two-way you can get your id, Let me know if you have any more questions and I'll try to clarify your points with more clarity.
You are not calling API correctly inside the Postman. You should call it like this:
http://localhost:3000/api/v1/users/120622
In the router file, what you are using is Route Parameter where the valid URL would be http://localhost:3000/api/v1/users/120622. for your Postman api to work you should remove :id at router file

How to create an express update route with multiple parameters

I want to update an attribute within a JSON object using fetch PUT. I've created a put function taking in 2 URL parameters
app.put('/trustRoutes/:id/:item', (req, res){
I am able to update the data with a single parameter but since I only want to change one value inside that object, calling put will replace the whole object with my new body.
below is what I've tried.
app.put('/trustRoutes/:id/:item', (req, res) => {
readFile(data => {
const userId = req.params['id/item'];
// have also tried const userId = req.params.id.item
data[userId] = req.body;
//write data back to file
I looked around at other examples but couldn't find any that were updating data instead of GET. If there is one I missed please let me know.
PUT requests are great for completely overwriting a resource, and is idempotent. This answer does a good job explaining idempotency. For updating a resource partially, a PATCH request is a better choice.
app.patch('/trustRoutes/:id/:item', (req, res) => {
readFile(data => {
data[userId] = req.params[id];
data[item] = req.params[item];
// A get request for this resource would now show both of the updated values
// Write file

Getting error 404 for put request (using express and node js) [duplicate]

I am trying to create two routes in my express app. One route, without a parameter will give me a list of choices, the other one with a parameter will give me the choice related to the id.
router.get('/api/choice', choice_controller.get_choices);
router.get('/api/choice/:id', choice_controller.get_choice);
When I go to .../api/choice/?id=1 the api returns the list of choices, and therefore follows the route without the param (/api/choice). How do I make sure that the router does not omit the parameter?
Thanks in advance.
UPDATE
It seems that it does not fire the /api/choice/:id route. If I remove the one without the param, it gives a 404 so. Could someone explain to me why /api/choice/?id=1 is not getting picked up by /api/choice/:id?
Basically, your declared routes are documented in the Express documentation.
The second route is resolved by a URL like /api/choice/hello where 'hello' is mapped into the req object object as:
router.get('/api/choice/:id', function (req, res) {
console.log("choice id is " + req.params.id);
});
What you are actually trying is mapping query parameters.
A URL like /api/choice/?id=1 is resolved by the first router you provided.
Query parameters are easy to get mapped against the request as:
router.get('/api/choice', function (req, res) {
console.log('id: ' + req.query.id);
//get the whole query as!
const queryStuff = JSON.stringify(req.query);
console.log(queryStuff)
});

Express Routing Params

I am looking to get this query from this url 'http://localhost:3000/#/quote/edit/?quote_number=1&line_number=1'
from this route in express
router.route('/quote/:quote_number&:line_number')
.get(checkAuthentication, (req, res) => {
let request = new sql.Request(pool)
let get_lines_query = `
select *
from quote_line
where quote_number = ${req.query.quote_number} and
line_number = ${req.query.line_number}`
but it is calling a different query from
route router.route('/quote/:quote_number')
Firstly, the URL you provided doesn't match the route. Your route is to /quote/number&line but your URL is of the form /quote/edit/?quote_number=number&line_number=line.
Secondly, parameters written as ?key=value&key2=value2 are called query parameters, and being special, standard forms of parameters, you don't need to bind them yourself. Express will parse them into the req.query object without you specifying the bindings. So all you need to do is change your route to /quote/edit and you're good.
On an unrelated note, please don't directly stick URL parameters into your SQL query. That's how you end up with SQL injection attacks. Depending on the SQL package you're using, there should be a way to use bound parameters in your queries instead.
Try updating your code to:
router.route('/quote/:quote_number/:line_number').get(function (req, res) {
let quote_numer = req.params.quote_number;
let line_number= req.params.line_number;
res.send(quote_numer + "" + line_number)
})

Express server route format

I have two different types of possible API class I can make.
The first one is:
http://api_url.com/api/v1/schools/countries/BR
and the second one is:
http://api_url.com/api/v1/schools/countries/BR?admin1=MA
My route in backend/routes/schools.js is:
router.get('/countries/:country', forward_get);
const forward_get = (req, res, next) => {
console.log(req);
const url = `${url}${req.originalUrl}`
getResponse(url, acToken, res);
}
How do I make it so that I am able to also make the second api call and get the appropriate parameters "admin1: MA". Ive gone through the whole req object and I don't seem to find them anywhere. So far I've been able to make the first api call without a problem.
This is the only route you need:
You access admin1 using req.query.admin1
and
You access country using req.params.country

Categories

Resources