I want to use router functionality of node to call server side methods. I am not using express generator to generate project structure.
I made some changes to the code in the answer by Mukesh Sharma and made it work:
Server.js (Server code)
var express = require('express');
var app = express();
var routes = require('./FirstAppServer/route');
app.use('/', routes);
// //set static folder
app.use(express.static('FirstApp/public'));
app.use('/module', express.static('node_modules'));
app.listen(3000, function () {
console.log('Port 3000');
});
app.get('/', function (req, res) {
res.redirect('login.html');
});
module.exports = app;
route.js
var express = require('express');
var router = express.Router();
router.post('/endpoint', function (req, res, next) {
console.log('Server side call');
next();
});
module.exports = router;
test.html
<!doctype html>
<html>
<head>
<title>Login</title>
<script src="js/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
testServerCall();
});
function testServerCall(){
debugger;
$.ajax({
type:"post",
url:"/endpoint",
data:{
"a":"a"
},
success:function(){
console.log('success');
},
error:function(){
console.log('error');
}
});
}
</script>
</head>
<body>
<div id="divLogin">
<input type="text" id="txtUsername" />
</div>
<h2>Login</h2>
Create User
</body>
</html>
You can define routes in different file and can import in the server.js .
server.js - Server code
var express =require('express');
var apis = require('./api.js');
var app = express();
app.use('/api', apis);
app.listen(3000);
api.js - Api router
var express =require('express');
var router = express.Router();
router.get('/users', function (req, res) {
return res.json([{
name: 'John Doe',
email: 'john#doe.com'
}]);
});
module.exports = router;
Hope it helps you.
Related
I am having one simple vue file (index.html)
<html>
<body>
<div id="example">
<p>{{ hello }}</p>
</div>
</body>
</html>
<script src="js/app.js"></script>
<script>
new Vue({
el: '#example',
data: { hello: 'Hello world!' }
})
</script>
When opening the index.html file in browser, it is printing Hello world. I need to deploy this in express server. Added server.js file as below,
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 1234;
// sendFile will go here
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port);
console.log('Server started at http://localhost:' + port);
When running node server, browser is just rendering like below,
If I replace the <script src="js/app.js"></script> with <script src="https://cdn.jsdelivr.net/npm/vue#2.6.14/dist/vue.js"></script>, it is working fine. Dont know why it is not working when using Vue library as external file. Is there any way to achieve this? Thanks in advance.
Just add this line of code
app.use(express.static(path.join(__dirname, 'public')));
So you code would look like this
const express = require('express');
const path = require('path');
const app = express();
const port = process.env.PORT || 1234;
app.use(express.static(path.join(__dirname, 'public')));
// sendFile will go here
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/public/index.html'));
});
app.listen(port);
console.log('Server started at http://localhost:' + port);
Please can you help me out, for some reason I am not able to post and am getting a "cannot POST /api/create" and when inspecting the page a 404 error is shown.
Here is my index.js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mainRouter = require('./mainRouter.js');
var todoRoutes = require('./todoRoutes.js');
//tell express to use bodyParser for JSON and URL encoded form bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//mouting our routers
app.use('/', mainRouter);
app.use('/todo',todoRoutes);
app.listen(3000);
console.log("Express server running on port 3000");
And the corresponding todoRoutes.js file is where I require the post method:
var express = require('express');
var todoRoutes = express.Router();
var todoList = []; //to do list array
todoRoutes.get('/', function(req, res) {
res.sendFile(__dirname + '/views/todo/index.html');
});
todoRoutes.get('/create', function(req, res) {
res.sendFile(__dirname + '/views/todo/create.html');
});
todoRoutes.get('/api/list', function(req, res) {
res.json(todoList); //respond with JSON
});
todoRoutes.get('/api/get/:id',function(req, res){
res.json(todoList[req.params.id]);
});
todoRoutes.post('/api/create', function(req, res){
console.log("Creating the following todo:", req.body.todo);
todoList.push(req.body.todo);
res.send({redirect: '/api/list'});
});
and here is the corresponding html file:
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Todo List: Create</title>
<meta charset="utf-8" />
</head>
<body>
<form action = "/api/create" method="post">
<div>
<label for="todo">Enter your new Todo:</label>
<input type="text" id="todo" name="todo">
</div>
<div class="button">
<button type="submit">Add</button>
</div>
</form>
</body>
</html>
If I put a console.log("") in the POST function of the todoRoutes.js file it will not be displayed, indicating that the function does not even get executed.
Any help will be very much appreciated.
You need to POST to /todo/api/create, based on your current route handling:
<form action = "/todo/api/create" method="post">
I am trying to create and start a server and I've been looking at other code and can't see why mine isn't working (just getting this: localhost just keeps loading and loading and nothing happens).
Any ideas? Thanks!!!
app/server/app.js :
'use strict'
var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');
var app= express();
module.exports = app;
app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = http.createServer();
server.listen(1337, function () {
console.log('Server is listening on port 1337!');
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);
});
app/browser/index.html :
<!DOCTYPE html>
<html lang="en">
<head>
<title>node</title>
</head>
<body>
<div>
<p>Hey whats up</p>
</div>
</body>
</html>
Your code works for me.
The only thing wrong in your code is you have to change server.listen(1337, function ()..., to app.listen(1337, function () {...
Also, I added a file path...
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));})
...to link your localhost:1337 to your index.html file. Now your index.html file will display when you go to localhost:1337.
Lastly, I'm not sure if you need this line... var server = http.createServer();. I deleted it and everything worked fine.
Here's the code below.
'use strict'
var express= require ('express');
var path=require('path');
var bodyParser = require('body-parser');
var http = require('http');
var app= express();
module.exports = app;
app.use(express.static(path.join(__dirname, '../browser')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, '/index.html'));
})
app.listen(1337, function () {
console.log('Server is listening on port 1337!');
});
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send(err.message);
});
Maybe the port You wrote - 1337 is busy, check by choosing other port, for example 4200, or 3000 - server.listen(4200,function () {
It's probably a newbie question. I'm trying to setup my very first expressjs application and I need to use a view helpers that doesn't work for some reason.
Here is my server.js
var express = require('express');
var app = express();
var test = function(req, res, next) {
res.myLog = function(){
console.log("res");
return "Hello";
}
next();
}
app.use(test);
app.get("*", function(req, res) {
res.sendfile('./dist/index.html');
})
app.listen(5000);
And index.html
<html>
<head>
<title>Test application</title>
<link rel="stylesheet" href="main.css" />
<script src='<%=myLog()%>'></script>
</head>
<body>
<h1>Yo World!</h1>
</body>
</html>
myLog function is not call during rendering. Originally I was trying to use some third part helpers and they didn't work as well.
I haven't found any documentation of how to use the helpers on expressjs site. I'm clearly doing something wrong here.
Express version 4.3.14
To send file using express, correct ways is:
//sending html files
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:5000
app.get('/', showClientRequest, function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
function showClientRequest(req, res, next) {
var request = {
REQUEST : {
HEADERS: req.headers,
BODY : req.body
}
}
console.log(request)
return next();
}
app.listen(5000);
Use ejs template engine:
var express = require('express');
var ejs = require('ejs');
var app = express();
app.set('view engine', 'ejs');
var path = require('path');
// viewed at http://localhost:5000
app.get('/', showClientRequest, function(req, res) {
res.render('index',{message:"Hello World!"});
});
function showClientRequest(req, res, next) {
console.log('Something Here...');
return next();
}
app.listen(5000);
Node-Cheat Available:
For complete code, get working node-cheat at express_server run node app followed by npm install express ejs.
Use res.locals.myLog instead of res.myLog to set locals. If you don't need req within your helper function you can also use app.locals.myLog.
res.sendfile will not render your view but just send a file as it is. You will have to use res.render and move your dist/index.html to views/index.ejs.
This is my app structure
controller
routes.js
public
jquery.js
socket.io.js
app.js
index.html
The app.js file contains the socket program which emits the some message when user connects. Now the problem was how I emit the message from routes.
My nodejs code was below:
This is my app.js file code:
var express=require('express');
var app=express();
var server=require('http').createServer(app);
var io=require('socket.io').listen(server);
app.use('/', express.static(__dirname + '/'));
io.sockets.on('connection',function(socket){
socket.emit('message',{msg:'hai'});
});
app.use('/cal',require('./controllers/route'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
server.listen(3000);
This is my route.js code:
var express=require('express');
var route=express.Router();
route.get('/',function(req,res){
//socket.emit('message',{msg:'hai'});
});
module.exports=route;
This is my index.html file code:
<htmL>
<head>
<title>Chat with socket.io and node.js</title>
</head>
<body>
<script src="./public/jquery.min.js"></script>
<script src="./public/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
socket.on('message',function(data){
alert(data.msg);
});
});
</script>
</body>
</html>
Thank You.
Routes has nothing to do with sockets. You have to listen on sockets, not on routes. Here's par of the docs (http://socket.io/docs/) for using Socket.IO with Express:
// server - app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
// client - index.js
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>