I have created a simple page that you login with a service and it gets the accounts username using nodejs. I then give the user a file that look like this:
<html>
<body>
<p>Hello <span id="user">user-placeholder</span></p>
</body>
</html>
Index.js: (assume user is logged in as they are)
app.get('/authorized', functiong(req,res){
console.log(accountInfo.username);
res.sendFile(file);
});
I just want to update the span that has id user with accountInfo.username.
I'm not sure how exactly to update this value.
You should use a template engine like pug by running:
npm install pug --save
Then you index.pug in the views directory
html
body
span Hello
span= user
Then modify your route little bit to look like this:
app.get('/authorized', function (req, res) {
res.render('index', { user: accountInfo.username });
})
For more details https://expressjs.com/en/guide/using-template-engines.html
Related
I am working on making a Nodejs application and was able to successfully allow a user to register, store their information in a MongoDB database, and allow them to login. However, I am having trouble getting the user's name to display on every page after they login. To my understanding, I should use something like so:
res.render("./home/about", {
name: req.user.name
});
I do however have to have the user logged in to be able to grab that name, otherwise, it will error. I was wondering if there was a workaround to this so I am able to display the username on every page?
This is the link to my git repository: Github llink
I would appreciate any help.
Note I currently do not have the html code where I would display the users name and have removed the chunk of code displayed above.
Image showing added code:
Shows I have access to users name on about page but not home page.
SOLVED:
By placing the following code in my app.js file:
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
I was able to attain access to all data attached to the user object. In order to check if it is valid, I would do the following:
<% if(user){ %>
<a>Welcome, <%= user.name %>!</a>
<% } %>
NOTE The '<% %>' are 'ejs' tags that allow me to use javascript within my HTML code.
By placing the following code in my app.js file:
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
I was able to attain access to all data attached to the user object. In order to check if it is valid, I would do the following:
<% if(user){ %>
<a>Welcome, <%= user.name %>!</a>
<% } %>
NOTE The '<% %>' are 'ejs' tags that allow me to use javascript within my HTML code.
I'm trying to integrate MailChimp's API into my React App which will allow users to authorize their MailChimp accounts for use in my app. I haven't found a tutorial on it, so I'm following this tutorial which uses only express: https://www.codementor.io/mattgoldspink/integrate-mailchimp-with-nodejs-app-du10854xp
I've gone through Mailchimp to set up my app/my client secret/client id, etc:
Redirect URI
```http://127.0.0.1:3001/mailchimp/auth/callback````
I kept the same express code as the tutorial, except I put my client secret in a .env file:
server.js
const querystring = require('querystring');
const mailchimpClientId = `${process.env.MC_CLIENT}`
app.get('/mailchimp/auth/authorize', function (req, res) {
res.redirect('https://login.mailchimp.com/oauth2/authorize?' +
querystring.stringify({
'response_type': 'code',
'client_id': mailchimpClientId,
'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback'
}));
});
However, in the tutorial, the callback function is in an HTML file written like this:
<!doctype html>
<html>
<head>
<title>Integrate MailChimp</title>
</head>
<body>
<a class="btn btn-primary" href="/mailchimp/auth/authorize">Connect with MailChimp</a>
</body>
</html>
I've added this (using JSX syntax):
MailChimp.jsx
class MailChimp extends Component {
render() {
return (
<div>
<h1>MailChimp Auth</h1>
<a href={'http://127.0.0.1:3000/mailchimp/auth/authorize'}>Mailchimp</a>
</div >
)
}
}
export default withRouter(MailChimp);
On clicking that link inside my React App's route localhost:3001/mailchimp, I'm sent to mailchimp where I sucessfully login with my account (not the one requesting permission) and I am returned to the react app.
However, I'm getting the following error:
GET /mailchimp/auth/callback 404 2.818 ms - 162
Failed to load resource: the server responded with a status of 404 (Not Found)
I've scoured the web trying to find a working example of using React & Express for MailChimp Oauth for app authorization but I haven't found one. My question is, did I set something up wrong in the redirect, or is there a better recommendation for handling this request in React?
The 404 error is saying that you don't have a route that maps to /mailchimp/auth/callback. Looks like from your code you haven't written that.
Unless you haven't provided the code for it, you need the route handler mentioned with the code in the tutorial:
app.get('/mailchimp/auth/callback', function(req, res) {
request.post('https://login.mailchimp.com/oauth2/token')
.send(querystring.stringify({
...
}
I'm creating an app using laravel + vue. Vue loads all the javascript codes in the app.js even in the login page in which the user is not yet authenticated. I don't want to expose all the js codes just yet until user is logged in. Is there any way that I can only show the necessary codes for the login page and not expose all the js code of the app? I'm doing this to also limit the size of app.js being downloaded for the login page to improve page loading time too.
If you're using Laravel mix, you can add a new entry point for your login script.
mix.js('resources/assets/app/js/app.js', 'public/app/js')
.js('resources/assets/app/js/login.js, 'public/app/js);
So, you can add a #yield statement in your base layout to place scripts declared in the page view.
base.blade.php
<html>
<head>
<title>App Name - #yield('title')</title>
</head>
<body>
#section('sidebar')
This is the master sidebar.
#show
<div class="container">
#yield('content')
</div>
#yield('scripts')
</body>
</html>
login.blade.php
#extends('layouts.base')
#section('title', 'Page Title')
#section('content')
<p>This is my body content.</p>
#stop
#section('scripts')
<script src="{{ mix('app/js/login.js') }}"></script>
#stop
Edited
For a SPA you can have another bundled entry point to just define the Login component:
Vue.component('login-form', {
... component code here
})
You can use vue-plugin-load-script to load the login.js script in the beforeEach method from Vue router. So the component will be available before render the login page.
router.beforeEach(async (to, from, next) => {
if (to === 'login'){
await Vue.loadScript('login entry point url here')
}
next();
});
Also, you can do it inside the page using the beforeMount hook. Here an example using a fake promise and entry point.
https://jsfiddle.net/7oj2sxun/3/
If you're using Vue CLI, it already supports lazy loading with dynamic imports.
Here a detailed article:
https://blog.logrocket.com/lazy-loading-in-vue-js/
Currently building a Single-page App with Node, with user authentication using passport and mongodb. I want to be able to send the user messages like "that username is already taken" or "please fill out all fields" on signup and login. However, all of the examples of this I have seen use a templating engine with a package like flash to render html based on javascript sent from the server. Is there a way around this? My app is pretty far along, and switching to a templating service is going to be a real pain. I don't need to render html, a simple alert box will suffice.
You can create controller action that matches the route and manually pass found model to the view.
In UserController:
find: function(req, res) {
User.findOne({'id': req.params['id']}, function(err, user) {
res.view({user: user})
})
}
Then You can reference this model in views/user/find.ejs:
<%- user.id %>
<%- user.name %>
use the above syntax to give alert();
I hope this is what you are looking for!
Is there any way using express + swig template for nodeJS to pass variables from the server side to client side javascript? I know it can be done in Jade but I'd rather stick with a template engine that more closely resembles HTML. Thanks for the help guys!
OK I will assume that you could configure your express with consolidate.swig if not please read this link (http://tinyurl.com/kcs8kvy).
Well I didn't find the direct way to pass variable values to client javascript but I have found a workaround.
for instance you're sending an object, in your route at express:
app.get("/", function(req, res){
var myUser = { name: "Obama" };
res.render("index", {user: myUser});
});
then in your index.html file you can create a script tag:
<html>
<body>
<script>
var username = "{{user.name}}";
</script>
<script src="whatever.js"></script>
</body>
</html>
and then in your whatever.js file the username variable will be available with its correct value. I hope that this help you.
To pass json objects from backend server to the template you can do:
var data = {{jsonData|raw|json}}