The normal get
method works fine on my main server.js
file. I also use server.get('/favicon.ico', (req, res) => res.status(204));
to tackle the issue of the favicon request. It works well, again only on my main server.js
file.
When I try to separate the code, by creating a user.js
file that handles the api calls, I get:
::ffff:127.0.0.1 - GET /favicon.ico HTTP/1.1 404 150 - 1.669 ms
::ffff:127.0.0.1 - GET /users HTTP/1.1 404 144 - 0.454 ms
This is my main file - server.js
:
const express = require('express');
const morgan = require('morgan');
const server = express();
const router = require('../routes/user');
const mysql = require('mysql');
server.use(morgan('short'));
//server.use(express.static('../public'));
server.use(express.json());
server.use(express.urlencoded({ extended: false }));
router.use(router);
server.get('/', (req, res) => {
console.log("Test!");
res.send("This works!");
});
//server.get('/favicon.ico', (req, res) => res.status(204));
server.listen(3003, () => console.log('Program is running! Port: 3003'));
This is my user.js
file:
const express = require('express');
const mysql = require('mysql');
const router = express.Router();
router.get('/users', (req, res) => {
res.send('Hello');
});
router.get('/favicon.ico', (req, res) => res.status(204));
module.exports = router;
I'm not sure if this is related but I also experience the same problem when trying to server.use(express.static('../public'))
. It doesn't work. I cannot serve my html file. I've tried using the csp headers when requesting but that doesn't work. Setting up a CSP policy in the html header
meta tag is not working either.
These are the versions of certain modules and technologies if you see a problem in any of their versions:
Apache 2.4.39
Node 6.9.0 Windows 7 - Yeah I know but bear with me
If anyone can help with eigther the router issue or the static file server issue it would much appreciated.
Thank you.
A simple way to do this is, in your server.js file add
server.use("/user", require("./routes/routes"));
note: routes is a folder here and routes.js is a file inside that folder.
then in your route.js file add
const express = require('express');
const router = express.Router();
const user = require('../controllers/user.controller');
// register controllers
const userController = new user();
userController.register(router);
module.exports = router;
pass your router in the user register(router) method. and it will be easily accessible in your user.js file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.