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');
Related
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"));
I have search a lot and I can't seem to start express js app. All I'm getting is 404 error.
Default app.js file which has http server and it works fine.
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(response);
});
server.listen();
And this is express js code which is not working. giving me 404 error.
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
server.listen();
I also tried few other combination as well.
var express = require('express');
var app = express();
app.get('/', (req, res) => res.send('Hello World!'));
var http = require('http');
var server = http.createServer(app);
server.listen();
this one also didn't work
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => res.send('Hello World!'));
server.listen();
I also tried expressjs to create it own server and it also didn't work.
const express = require('express');
const app = express();
const port = 80;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I also tried to remove port from app listen and not surprisingly it also didn't work.
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World!'));
app.listen();
I also tried everything from express-js-app-listen-vs-server-listen page but not successful.
This is the error I get
For others with the same A2 Hosting issue, the solution is actually so easy...
The problem with the application running the NodeJS deployment on cPanel. Phusion Passenger does not use the root path as '/', but as '/yourAppURL'. So in your NodeJS code, you have to add the specified AppURLPath to the call when using Express...
e.g.
//Instead of
app.get('/', (req, res) => res.send('Hello World!'));
//Change to
app.get('/YourSpesifiedAppURLPath/', (req, res) => res.send('Hello World!'));
I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});
I have this router (http/api/ping.js):
var express = require('express');
var router = express.Router();
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
module.exports = router;
This router is embedded into this router (http/api/index.js):
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('You called /api');
});
router.use('/ping', require('./ping'));
module.exports = router;
And this router is used by my Express.js app (app.js):
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;
// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);
// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));
// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});
module.exports = {
app: app,
server: server
};
When I run the app, /api returns You called /api, but /api/ping gives me a 404.
I am using Node 6.9.1 and Express ^4.14.0
I think order matters in this scenario. Try putting /ping above the / get route.
router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
res.send('You called /api');
});
Also in your ping route you say the path to your route is /ping you also say it is /ping when you import it to the other router, which would make the path /api/ping/ping
change
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
to
router.get('/', function (req, res) {
res.send("You called /api/ping");
});
I think your routing is incorrect on this line
router.use('/ping', require('./ping'));
this will point to http/api/ping/ping
it should be
router.use('/', require('./ping'));
I have this code:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
I will have many services (like the test one), and I don't want to have them all on the same file.
I read in another question in Stack Overflow, that I can require other files like this: var express = require("./model/services.js"); And in that file write all the services, but it's throwing app is not defined when I start Node.
How can I separate codes?
You can define your routes in different files say test-routes.js like this:
module.exports = function (app) {
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
}
Now in your main file say server.js you can import your route file like this:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
// import your routes
require('./test-routes.js')(app);
your test.js should look something like:
var express = require('express');
var router = express.Router();
router.get('/test', function (req, res) {
res.json(200, {'test': 'it works!'});
});
module.exports = router;
and the app.js (assuming other is some other route defined similarly to test.js):
var test = require("./routes/test.js");
var other = require("./routes/other.js");
...
//all your code for creating app
...
app.use('/test', test);
app.use('/other', other);