I am using nodejs server to run my app along with express-handlebars engine as view engine . I wonder how can I use javascript code in the view in order to manipulate data given by the server as illustrated below :
// from server
app.get("/newcalendar", (req, res)=>{
rdv.find().
then(data=>{
res.render("newcalendar", {servData:data});
})
.catch(error=>{
return console.log(error)
})
});
// to view : newcalendar.hbs , I want to use javascript to manipulate the recieved data :servData
<div>
{{#each servData}}
{{this}} // how can I manupulate this using javascript ?
{{/each}}
</div>
Related
I'm developing an app that has the backend and frontend as part of a single project and the backend, aside from being the API, it also serves the static files for the frontend by doing this:
const frontendDir = appRoot.resolve("../frontend/build")
app.use(express.static(frontendDir))
app.get("*", (req, res) => res.sendFile(path.resolve(frontendDir, "index.html")))
Is there a way to somehow pre-process those files before sending them to inject some of the environment variables the server has access to but the client obviously doesn't?
I'm trying to make some variables accessible, like SENTRY_DSN, HEROKU_RELEASE_VERSION, HEROKU_RELEASE_CREATED_AT, etc.
I don't know this would help but I think you could use a template engine for passing your data to the front end .like handlebars :
const Handlebars = require('handlebars')
Handlebars.registerHelper('prod', () => {
return process.env.NODE_ENV === 'production';
})
in your html file:
<div class="some-content">
{{#if prod}}
<p>Seen only in production</p>
{{/if}}
<p>This is some example text</p>
</div>
I am new in ExpressJS, I know how to pass data from backend to the an ejs page, but I wanted to know how to pass data to a js file in the public folder?
So to pass data to a js file ( which js file is in the same folder as ejs ) while rendering the ejs page in the same time .
From ExpressJS I pass data to ejs by rendering ejs page like this
exports.user_signup = (req, res, next) => {
res.render('login', { page:'Login', email: req.body.email, idd: user[0]._id,} );
}
The ejs file :
<script src="file1.js"></script>
<%= email %>
So what I want, is to pass some data from ExpressJS to file1.js (which is in public folder)..
You cant access ejs data in a Javascript file or pass in data to a js file.
One possible way, Is that you can make use of variable passed to an ejs file.
Copy in your JS code to your ejs file and enclose them in a <script> tag.
pass in your required data to the ejs file ( in our case index.ejs ).
res.render('index', {data: 'some data'});
Inside the <script> tag in ejs file you can access the data like.
<script>
var x= <%- data %>;
console.log(x);
</script>
I am trying to create a simple form handler using express. Here is a similar question but I can't related it with my problem. I have written all of my file Here anyone can check it by using all of my file. For better understanding I copy my code here:
app.js code:
const express = require('express');
const app = express();
//routes
app.get('/',function(req,res){
res.send('This is root dir');
});
app.get('/friends',function(req,res){
var friends=['sakib','emon','rayhan'];
res.render('friends.ejs',{friends:friends});
});
app.get('/addfriend',function(req,res){
res.send('ADD friend page launch!!!!!');
});
app.listen(3000,function(){
console.log("server has started on port 3000!!!");
});
ejs(friends.ejs) code:
<h1>Here is list of your Friend:</h1>
<%friends.forEach(function(friend){%>
<li><%=friend%></li>
<%});%>
<form action="/addfriend" method="POST">
<input type="text" name="friend" placeholder="name">
<button>
Submit
</button>
</form>
When I type any name in the input box and clicked Submit it didn't post to /addfriend. I didn't understand where is my problem. Please goto input box(link) after started the server.
For better understand what's my actual problem is then please use goorm IDE(shared file) where I uploaded everything.
You are using get request instead of post for addfriend.
app.post('/addfriend',function(req,res){
console.log("I'm called wohoo!");
res.send('ADD friend page launch!!!!!');
});
My LoginController.js looks like this:
module.exports = {
getAuthorizationLink: function (req, res) {
res.send({
authorization_link: sails.config.FACEBOOK_LOGIN_URL
})
}
}
I need to redirect to the authorization_link when a button is clicked
<div class="col-md-4 text-center">
<button id="authenticate" class="btn btn-primary">Authenticate Page</button>
<script type="text/javascript">
document.getElementById("authenticate").onclick = function () {
...
};
</script>
</div>
Here you are looking to mix server-side (EJS) & client-side JS code.
It is possible, makes sense to do sometimes but it is not clean.
Once you understand you are doing this. Variable can be passed and accessed.
Using EJS, write JS code for client side e.g.
var auth_link = '<%= authorization_link %>';
this line will become something like below for client-side JS
var auth_link = 'https://fb.com/login';
Now you can use auth_link in client-side JS as required
Also, check res.view for responding with HTML page
I am creating a Node.js application with AngularJS.
I want to make a simple POST, using Angular. This POST should post a couple of values to my server, where I can see them using console.log.
In my HTML code, I build it with the ng-model and a button that has a ng-click.
I can tell my Node.js server is being hit, as it outputs the post called in the console.
However, I have been trying to read about how to read the POST values, but I haven't found a solution.
How would I modify my code to read serialKey and gameTitle in my Express.js endpoint?
My HTML code:
<div class="input-group" ng-controller="CreateController">
<p>Serial key:<br/>
<input class="form-control" ng-model="serialKey" />
</p>
<p>Game:<br/>
<input class="form-control" ng-model="gameTitle" />
</p>
<span class="input-group-btn">
<button class="btn btn-default"
ng-click="postNewIsbn(serialKey,gameTitle)">Add</button>
</span>
</div>
Angular controller code:
app.controller('CreateController',function($scope, $http) {
var url = '/api/serials';
$scope.postNewIsbn = function(serial, game) {
$http.post(url, {
serial: serial,
gametitle: game
})
.success(function (data) {
$scope.data.status = 'success';
})
.error(function(error) {
$scope.data.error = error;
});
};
});
Express.js endpoint
app.post('/api/serials',function(req,res){
console.log(req.body);
console.log('post called');
});
It appears to be the problem of setting content-type header. In your angular application you can set defaultHeaders for your post request just after you initialize the module or in your config function with this line
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
Do remember to inject the $httpProvider dependency whereever you setting this header
UPDATE
It may be the case that you need to configure your express in order to use the bodyParser with this line:
app.use(express.bodyParser());
req.param(name)
When attempting to retrieve data passed with the request, the req.param() function checks the following in order to find the parameter:
req.params
req.body
req.query
See the docs here.
Also, try explicitly setting the content-type header in the POST request to "application/json".