Send data from nodejs to ejs? - node.js

Can we send data to another client ejs i's, in another server?
I tried to do:
res.render('/visi-web/home/www/elasticsearch/views/index.ejs', {result:result});
And that's not working.
var elasticsearch = require('elasticsearch');
var express = require('express');
var app = express();
var http = require("http");
var server = http.createServer(app);
app.get('/', function(req, res){
...
res.render('/visi1-sih-web/home/www/elasticsearch/views/index.ejs', {result:result});
});
}
});
server.listen(3333);

Well,you doing it wrong way.
After looking your code,When you hit '/',it load index.ejs .There is no need to give detail path.
Use following syntax.
app.render('index', { result: 'result });
When you set your template engine to ejs or something else, there is no need to give extension.
Also ,Please check your view path is defined or not containing index.ejs.
Just give relative path for index.ejs.
means if you say
app.use(express.static(__dirname + '/public'));
and within publlic folder there is view folder,then you should written in this way.
app.render('view/index', { result: 'result }).
No need to give public folder name in path.

Related

Serve ReactJS app with JSON data pre-populated

I would like to serve up a ReactJS Single Page App from a nodeJS server and pass up some JSON data at the same time.
I have user credentials and some other user specific data that i would like pre-populated into my page and avoid making multiple round trips to the server.
How do i pass a JSON object to the client at request time and have it available to my React app
var path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT;
app.use(express.static('dist'));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '../../dist/index.html'));
});
app.listen(port, () => console.log(`Running on port ${port}.`));
I can suggest you add a script tag into your index.html file. Like below
<script>
window._DATA_={ key: 'value', .....}
</script>
Now in your react application, use the key window._DATA_ to get the data that you sent from the server. In this approach, the problem is that you can't send dynamic data.
To achieve that you may need to use the template libraries. For example pug, nunjucks, ejs, etc.
Below is the example of using pug.
Your express route will look like this.
app.get('/*', function(req, res) {
res.render('index', data);
});
// End of your pug file looks like
...
...
script.
var window._DATA_= !{JSON.stringify(data)}
If you want to add scripts files dynamically then you can use html-webpack-pug-plugin.
For more info
https://www.npmjs.com/package/html-webpack-pug-plugin

can not read image from folder in node.js

I have put images inside "/public/images" path. Now in the respose I am getting url as I wanted. But as soon as I paste that url to web browser, it says Cannot GET /public/images/food-1-xxhdpi.png. So should I write separate API to handle that?
Main file app.js
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
var PORT = 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var foodtruck = require('./model/datafoodtruck');
var db = mongoose.connect('mongodb://127.0.0.1:27017/quflip');
mongoose.connection.once('connected', function() {
console.log("Connected to database")
foodtruck.save(function(err,foodtrucks){
if (err) res.send(err);
});
});
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public/images'));
app.get('/foodtrucklist',foodtrucklist);
app.listen(PORT,function() {
console.log('express listining on port' + PORT);
});
This line
app.use(express.static(__dirname + '/public/images'));
Maps the static content in the /public/images folder to the root of your web application. So the request /public/images/food-1-xxhdpi.png will only work if the full path is .../public/images/public/images/food-1-xxhdpi.png
You should either make your request for /food-1-xxhdpi.png or change the line of code to something like:
app.use('/my-virtual-directory',express.static(__dirname + '/public/images'));
so that requests can be picked up in what ever you choose to make /my-virtual-directory
So... Your file in this case becomes /my-virtual-directory/food-1-xxhdpi.png
Obviously, you can still do this to make it map externally to the same way you have it internally with:
app.use('/public/images', express.static(__dirname + '/public/images'));
Here is more info on the static middleware for express: https://expressjs.com/en/starter/static-files.html
Try:
Backend:
var path = require('path');
var app = express();
var express = require('express');
app.use(express.static(path.join(__dirname, 'public')));
Frontend:
<img src="/images/food-1-xxhdpi.png" alt="">
You can try back-end look like this.
app.use(express.static(__dirname + '/public'));
Then front end use this extract location like
<img src="images/your image name" alt="" />
I am currently working on project and next snippet of code working fine for me:
app.use(express.static('public'));
and when I try to reach this in .hbs it is easy as:
<img src='/images/image.jpg' alt='...' />
Just type following code in your app.js file
app.use('/static/category/', express.static(__dirname+'/public/assets/category_pic/'));
now i will access image by using following code
<img src="/static/category/myimage.jpg" width="50" height="50">
here my actual path is /public/assets/category_pic/ but i convert it /static/category/ using above line of code
now i able to access image file using this url http://localhost:3000/static/category/myimage.jpg

ExpressJS Static not working

Been having some issues with express, I can't seem to serve static files.
If I do :
app.use('/*', express.static(DIST_FILEPATH));
it gives me a 301 or something, basically doesn't find the file (I have tried it in incognito mode also to avoid chasing/whatever issues).
But for some reason if I do:
app.use('/*', function (req, res, next) {
console.log(req.originalUrl);
console.log(DIST_FILEPATH);
res.sendFile(path.join(DIST_FILEPATH, req.originalUrl));
});
It works just fine and both paths are correct. Why is this happening and how can I solve it?
Express version: 4.14.1
Your issue is that you have the syntax slightly off. What you can do if you want to only server static files is use app.use(express.static(path.join(__dirname))); then when you go to http://localhost:3000/ you can add things like index.html so that you can see your html file. Here is an example of a simple express server that serves static files:
var express = require('express');
var path = require('path');
var app = express();
app.set('port', 3000);
app.use(express.static(path.join(__dirname))); //here you can change your path. for example you could add + 'public' if all of your files where in the 'public' directory
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
});
You can run this with node <filename>.js then just go to http://localhost:3000/index.html or http://localhost:3000/myMusicFile.mp3 for example.
hope this helps!

How to return a static xml file from nodejs server

I am integrating a 3rd party template which has a slideshow written using Mootools. The nodejs is configured with express and ejs
The data for the slideshow comes from a few xml files. For example data.xml. I placed the data.xml in public folder and added the following code to server.js (the main file)
app.use(express.static(__dirname + '/public'));
app.post('/data.xml', function(req, res){
res.contentType('application/xml');
res.sendFile('/data.xml');
});
Unfortunately this does not seems to work. I can see the file if I type the url
http://localhost:8080/data.xml
But the response I see in firebug is
" Cannot POST /data.xml "
I am assuming Mootools is trying to access the file using some POST method. Any suggestions for this problem?
when you are sending the file with sendFile() you need to point to the absolute address check this. note that I have the data.xml in the main folder.
you can access the file with localhost:8080/data (not localhost:8080/data.xml) and also as this is a post, you cannot access it through browser. use postman instead. or if you need it to be accessible on browser you need to change the protocol to get.
var express = require('express');
var path = require('path');
var app = express();
// you don't need this line!
// app.use(express.static(path.join(__dirname)));
app.post('/data', function(req, res){
res.contentType('application/xml');
res.sendFile(path.join(__dirname , 'data.xml'));
});
var server = app.listen(8080, () => {
console.log('Started listening on 8080');
});

Express wildcard rule

I am hosting a single page app with Node and Express. I use the static middleware for the client. I am using path URLs to navigate the app, for example domain.com/profile/134. I am using history.pushState to change pages internally on the client, and this works fine. What I am missing is a wildcard rule on the server to catch all possible paths when the user accesses my page directly to a path that is not root. If I try to access domain.com/profile/134 directly I get this: "Cannot GET /profile/134". I have tried to insert a wildcard get at the end of server.js, but it seems to be hit every time, also when I access the page root. This is my relevant code:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/../client'));
app.get('/*', function(req, res) {
console.log('wildcard');
});
Is this the correct GET wildcard rule to achieve what I need, and how can I serve the static client inside this handler? My client side will find the right page afterwards as long as the initial path is preserved. I basically want this wildcard rule to behave the same as the static rule, but keep the initial path.
You can use a hack
app.get('/:url', function(req, res) {
console.log('wildcard');
});
or try this one
app.get('/(.*)', function(req, res) {
console.log('wildcard');
});
[edited]: this should work as you expect:
var express = require('express');
var app = express();
app.get(/(.*)/, function(req, res) {
console.log("req.path", req.path);
res.send('success');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
I ended up using an npm module named express-history-fallback-api to solve this. Out of the box it solved both simple and advanced paths, like domain.com/settings and domain.com/profile/username
https://www.npmjs.com/package/express-history-api-fallback

Resources