I will explain more here so that it's clear what I am trying to do. I am creating a web application using Express.js and Node.js. I am trying to create a user profile at this moment. I have seen different way to render the user profile some websites goes like : Quora : https://www.quora.com/profile/************, Stackoverflow : https://stackoverflow.com/users/4056534/sandip-subedi and Facebook/Many other www.facebook.com/username.
I want to make something like what Facebook is doing. www.MYURL.com/USERNAME. How do I achieve that ? I know how to handle GET request and POST requests. There is a problem here because I already have more than 40 GET/POST request with different URL names. Since all of them are coming from www.MYURL.com/DOSOMETHING I couldn't figure out right way to filter if it is a user's profile or other URL. If I was doing something like www.MYURL.com/user/USERNAME it will be easy because I already know I am dealing with user at this moment.
You can create a router to namespace endpoints:
let router = express.Router()
router.get("/:username", (req, res, next) => {
// req.params will have the URL's username parameter
console.log("Request for user with username", req.params.username)
})
app.use("/user", router)
This mounts the username route on the user route: /user/[username]
https://expressjs.com/en/guide/routing.html
Related
I am working on an express application and I have two GET URLs. One fetches all resources in the database but is right-protected(needs authentication and admin access) while the other fetches resources based on a search parameter(query string).
The route that requires authentication looks like so:
carRouter.get('/car', verifyToken, isAdmin, fetchAllCarAds);
This means that the admin has to be logged in first and then a check is carried out to ascertain whether he is truly an admin before he is given access. Now I have another GET route that doesn't require authentication like so
:
carRouter.get('/car?status=unsold', filterUnsoldCars);.
I understand that express does not allow routing based on query strings so how do I ensure that the request that does not require authentication(query string) is accessible in the one without query string?
You can do the following things to make it work.
Check either query string exist or not inside isAdmin middleware
If query string exists, Skip validation that has been implemented inside middleware.
If query string doesn't exist, then check either user is an admin or not.
I fixed it by placing it before the verifyToken function and it worked. I would like to learn of other ways of doing it if there are. Thanks
carRouter.get('/car', filterUnsoldCars, verifyToken, isAdminDummy, fetchAllCarAds);
I dont think you are building a proper routing but, you can use a middleware to check query params and bypasses to the next route assigned. check below routing explanation for next('route')
Express Routing
carRouter.get('/car', hasParams, verifyToken, isAdminDummy, fetchAllCarAds);
carRouter.get('/car?status=unsold', filterUnsoldCars);
if hasParams true, next('route')
if hasParams false, next()
Am able to fetch html page properly using postman GET But getting error while fetching html page using POST using postman
Error details :
404 Not Found404 Not Found
We have frontend code on html/JS and backend code on nodeJS
This can happen for so many reasons. Check your imports, routes and request url.
Though it is not the way to get your html through POST method. Using GET method is the right way.
const express = require("express");
const router = express.Router();
router.post("/", (req, res, next) => {
res.render("index", { title: "Express" });
console.log(req);
});
module.exports = router;
It is good if fetch data using GET method only and if it is giving 404 Error then it means you might have not created any route with POST method. Same route with different method treat as different route like
1) GET http://example.com/fetch
2) POST http://example.com/fetch
are 2 different routes. You need to define each separately
I believe that for fetching data, GET is the preferred method and POST should be used to update server-side resources, not to retrieve them. If POST is returning 404, You may not have a POST route configured, or POST access may be disabled by itself through your server's configuration.
Usually the "GET" method is used when requesting the an html page, for example all the browsers, uses "GET" for requesting the landing page of any url.
Post usually is used to send data and logging in.
You need to create a route for POST requests to get the HTML.
I'm assuming that you must be using some kinda framework router like express-router to route your pages. In your router code, you would be having something like
app.get('/myHtmlPage', function(req, res) {
// some code
})
so you're getting your page back for making GET requests. You need to create a similar route like
app.post('/myHtmlPage', function(req, res) {
// some code
})
to get the same page for POST requests.
I've been working on this for the past day and can't seem to figure it out. I am using this Passport-Soundcloud to implement a soundcloud authentication. However what I don't understand is how I can get, and pass an authentication token to a front-end button push to like a sound.
My front-end code looks like:
function allowLike(){
$('.queueTrack').off('click').on('click', function(user){
console.log('clicked');
SC.put('/me/favorites/' + 21928809);
consol.log('sound liked')
});
};
Whenever I try to login through my app using the /login route, it works as expected and redirects me to my homepage. The problem is that I don't know how to get the oauth token from the passport-soundcloud so I can implement it into the front-end click event.
My routes followed the passport-soundcloud instructions and seem to work, but I can't figure out how to get the oauth token...
Any ideas? I'm totally lost on this.
So, I'm not familiar with the specific details of the soundcloud api. But if it follows the basic patterns of popular oauth apis. Then you'll want to do something like this.
User arrives at your site without a cookie
they authorize your app using oauth
when the user is redirected back to your app, SoundCloud will give you an access key for this user. Store this value, in a database or a cache or in memory. But most importantly, you must create a cookie on that users browser. So that when they return you can lookup the access key again.
When the user clicks like, lookup the accesskey on the backend and hit SoundCloud api with that token.
In the initial oauth flow....
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({
soundcloudId: profile.id,
token: accessToken // <--- store the token!
}, function (err, user) {
return done(err, user);
});
}
then when they click like
app.put('/me/favorites/12345' function(req, res) {
var id = req.user.id; // <--- passport and connect session saved the user id for you
// lookup the token in your database
// use the token to hit the soundcloud api
})
I hope this make some kind of sense. This is completely untested pseudo code.
[NODE, express] I am making facebook application, where after the user gives the facebook access , facebook redirects the user to my site with a code.
assume it to be
abc.com/heyBuddy/fb/callback?code="adasdasdasda"
In this route i.e router.get('/heyBuddy/fb/callback', funcion(req,res)) , i take the facebook code and do all the necessary computations on the server side, and i can render that data in a html file to the client using res.render.
But i dont want to render on the same url, i.e 'abc.com/heyBuddy/fb/callback' , I want to get the the user code on this url , do the computations and send that data to another url, i.e abc.com/heybuddy/fbApp and render from there, and so that the user sees the url = abc.com/heybuddy/fbApp.
I tried redirecting, but I was not able to send the computed data along so that i can render that data there.
Can anyone help, how can i got about this.
Sounds like you're reimplementing what is already existing with Passport.js and it's Facebook OAuth extension:
http://passportjs.org/
https://github.com/jaredhanson/passport-facebook
Try This :
function(req, res) {
// Successful authentication, redirect home.
res.redirect('/'); }
How do I determine which user has logged in in an express js application? I want to determine who is sending the request in my server program.
MeanJS stack
You can use req.user
exports.some_method = function(req, res) {
var user = req.user;
//do something
};
But you have to use users.requiresLogin to have persisted user
app.route('/model/:modelId').get(users.requiresLogin, my_controller.some_method)
It's implementation is pretty simple
exports.requiresLogin = function(req, res, next) {
if (!req.isAuthenticated()) {
return res.status(401).send({
message: 'User is not logged in'
});
}
next();
};
It's session based implementation indeed, but still good. That's it
Pure expressJS
You must use middleware that would detect current user by its cookie
It's more complicated indeed, and you have to write own implementation
But there are plenty of plugins, like passport, that would validate user by your fields. Also can serialize into req.user and vice versa
But i would strongly recommend to checkout MeanJS stack implementation, it's pretty easy to understand. As the name implies, it's MongoExpressAngularNode, so it's express based stack.
More
It depends on what kind of auth schema you are using, if it's REST, then you have to pass token in all requests to server, so that server checks db and get's user with corresponding token. If it's sessions based, then you can simple use any session based plugins. But the idea is same, when signing in, serialize user to session table, set cookie, when receiving request take cookie from requester, deserialize from session table, you got user now