I defined a route in my Express app that supposed to execute a line of code then return a JSON file, but what happens is that the file is returned, but the line of code isn't executed.
This is the server code:
var express = require('express');
var body_parser = require("body-parser");
var path = require('path');
server = express();
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
Inside index.html there is only a script tag defined like:
<body>
<script>
$(document).ready(function(){
$.getJSON("/request.json", function(data) {
console.log(data)
});
})
</script>
</body>
I can see the content of request.json file in chrome console, but the expected message "File "request.json" requested" isn't displayed on server's terminal.
Why the route isn't being executed?
The express.static is called before the /request.json route and already returns the file.
Use this:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
You can write custom static middleware. Can write logic to not to serve file[exclude].
Note: Note recommend from me, better change route name of /response.json
var express = require("express");
var path = require("path");
var app = express();
var statics = express.static(path.join(__dirname, "/"));
function customServe(secure) {
return function (req, res, next) {
console.log(req.path);
if (req.path != "/response.json") return statics(req, res, next);
return next();
};
}
app.use(customServe());
app.get("/response.json", (req, res) => {
console.log("something...");
res.send({ json: "json" });
});
app.listen(8080, () => console.log("working on 8080"));
Related
JS,
I have an express app with some routes. When my router doesn't match any route it will display index.html instead of going to route '/*' and redirect to a specific route.
I don't understand why my router doesn't go to app.get('/*') because when I type https://my-domain.com I want to be redirect to https://my-domain.com/test?id=1.
Maybe I can do something with express-static but I don't know how.
And if I name my file home.html instead of index.html it's work perfectly.
Here is a small piece of my code :
const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser");
const ejs = require('ejs');
const csrf = require('csurf');
const port = 3080;
let csrfProtection = csrf({ cookie: true })
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err)
res.status(403).json({error: "Invalid CSRF Token"});
})
app.post('/roles', csrfProtection, (req, res) => {
/*...*/
});
app.get('/test', csrfProtection, (req, res) => {
/*...*/
});
app.all('/*', csrfProtection, (req,res) => {
if(Object.keys(req.query).length == 0) {
res.redirect("https://my-domain.com/test?id=1");
}
res.render(path.join(__dirname + '/index.html'), {csrfToken: req.csrfToken()});
});
app.listen(port, () => {
console.log(`Server listening on the port::${port}`);
});
My files structure is :
home
static
css
js
index.html
index.js
At the request for https://my-domain.com, write res.redirect('/foo/bar'), where /foo/bar is the url you want to redirect to.
See Official Documentation For res.redirect(): http://expressjs.com/en/api.html#res.redirect
Very new to express and file system and don't have much idea about directories so getting this error.
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
app.use('/public',express.static(__dirname +"/public"));
Getting error "Cannot GET /public/signup.html"
My directories is:
-Express
--Server.js
--public
---signup.html
Looks like your code is a little jumbled up. Separate out your port listener - this should always come last. Add your routes and middleware before that as individual calls to app, and also register your get request to redirect back to your server to the signup html.
This should work:
var express = require("express");
var path = require("path");
var port = 2121;
var app = express();
// Register Middlewares/Headers
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Register Static
app.use("/public", express.static(__dirname + "/public"));
// Register redirect
app.get('/', (req, res) => {
res.redirect(req.baseUrl + '/public/signup.html');
});
app.listen(port, () => {
console.log("server Running on : ", port);
});
You're calling listen on app before you call use on your middleware and there are a few mistakes in your code. I think this should work:
app
.use('/public',express.static(`${__dirname}/public`))
.get('/', (req, res) => {
res.header({
'Access-control-Allow-Origin': '*'
});
res.redirect(`${req.baseUrl}/public/signup.html`);
})
.listen(2121);
You should provide
app.use('/public',express.static(__dirname +"/public"));
Before you using app.get
Full example:
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.use('/public',express.static(__dirname +"/public"));
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
oracledb.autoCommit = true;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
router.use('/' , function(req, res , next) {
console.log('Something is happening.');
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/insert')
.post(function(req, res) {
console.log(req.body);
console.log(req.body.c1);
console.log(req.body.c2);
});
app.use('/api', router);
app.listen(port);
In the example above ,when I try to log req.body it is returned as empty along with any of its properties.
EDIT: Maybe unrelated but when I try to test this REST API with a extension like Postman , it just keeps processing indefinately. ( Same thing happens with extension called DHC Rest)
I am learning node and express to create an api for an angular app I will be creating.
When I try and post something the req.body seems to be blank.
This is my server.js file
'use strict';
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
router = require('./api'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/my_db');
app.use(bodyParser.json());
app.use('/api', router);
app.get('/', function(req, res) {
res.render(__dirname + '/index.jade');
});
app.listen(3001, function() {
console.log('Listening on port 3001');
});
and this is my api/index.js file:
'use strict';
var express = require('express'),
Todo = require('../models/todo'),
router = express.Router();
router.get('/todos', function(req, res) {
Todo.find({}, function(err, todos) {
if(err) {
return console.log(err);
}
res.json({todos: todos});
});
});
router.post('/todos', function(req, res) {
var todo = req.body;
res.json({todo: todo});
});
module.exports = router;
when I use postman to post this to http://localhost:3001/api/todos:
{
'name': 'Walk the Dog',
'completed': false
}
my response is:
{
"todo": {}
}
I can't see why this would be blank, any help is appreciated.
UPDATE
Turns out I was posting text in postman instead of JSON.
use this in your server.js file
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());