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
Related
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)
});
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!
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
I'm making a Node.js server and I need to extract one part from a URL with this structure:
https://lets-talk-saku-gie-sakura.c9users.io/sala?extract
I just need the extract part.
I need to use the app.get method. However, the only way that I've found is:
app.get('/sala/:id', function (req, res) {
req.params.id;
});
This doesn't work; do you know how can I extract it?
req.params is for URL parameters like :id. Since you want a query parameter you should use req.query instead.
app.get('/sala/:id', function (req, res) {
console.log(req.query);
});
req.query might seem like a way to do this but, unfortunately, it's only useful when you know or expect certain query strings. Your best bet, I think, is to use req.originalUrl and then use a regular expression to find the part of the url you want to extract. See http://expressjs.com/en/4x/api.html#req.originalUrl
The nodejs HTTP doc has an example that can help you:
var obj = require('url').parse(req.url);
console.log(obj.query); // output: extract
I currently have an app which uses Express with Jade templates.
I'm building a new version of the app using Angular with client-side HTML.
I need access to certain request parameters in order to determine user permissions in my Angular code. My problem is that I don't know how to get ahold of these parameters in my Angular controllers/services.
Below is what currently occurs in Express with the Jade structure:
routes.js:
router.get('/player/:id',
playerRoute.show
);
player.js:
var show = function(req, res) {
res.render('player', {user: req.user});
};
...and now my new version's handler:
var player = function(req, res) {
//res.sendFile(path.join(__dirname, '../v2', 'index.html'));
res.json({user: req.user});
};
The correct user JSON is sent back to my client-side with the code above. When res.json is commented out and res.sendFile uncommented the correct HTML is rendered. My dilemma is how to both render this HTML AND provide my client-side Angular code with the user JSON object?
After all that, your question just boils down to:
MY dilemma is how to both render this HTML AND provide my client-side Angular code with the user JSON object?
You don't. The usual case is to just render the HTML along with the assets needed to render the initial app (hide everything, show a splash screen whatever). Further data (like getting your user) is handled by API calls to your server via Angular's HTTP facilities. That means they are separate. After that API call, your app determines what to render.
Otherwise, you could just render the data in the HTML as some global variable and have Angular pick it up from there. This is messy IMO, but doesn't require a separate API call to get the data.
copied from my own answer to a similar question
To get a variable from server to client javascript try templating a json string into the html and loading it from the javascript. EJS handles quote escaping and I think Jade does too. For reference content!= safeString tells Jade to skip escaping, so does content !{safeString}.
- var user={id:1, displayName:'foo'}
#example
meta(data-userJSON=JSON.stringify(user))
script(src="//code.jquery.com/jquery-1.11.3.min.js")
script.
var user = JSON.parse(
$('#example meta').attr('data-userJSON')
)
console.log(user);
span #{user.id}
span #{user.displayName}
Here's how I ended up handling this situation. I simply created a new API endpoint which I can easily hit with an Angular service. Here's the Node setup:
routes.js:
router.get('/currentUser',
apiController.currentUser.index
);
currentUser.js:
var index = function(req, res) {
res.json({user: req.user});
};
module.exports = {
index: index
};
Still seems odd to me to make an API call to get the request parameters, but it works. Feedback appreciated.