Node.js + Express路由未按预期工作

时间:2017-12-22 02:19:13

标签: javascript node.js mongodb express

我是Node.js的半新手,我对连接到我的本地主机并与MongoDB连接感到困惑。好像它忽略了我创建的路线。

首先,这是我的目录结构的快照。

enter image description here

这是我的package.json:

{
  "name": "summer_breeze",
  "version": "1.0.0",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-concat": "^1.0.1",
    "grunt-contrib-imagemin": "^1.0.1",
    "grunt-contrib-sass": "^1.0.0",
    "grunt-contrib-uglify": "^2.3.0",
    "grunt-contrib-watch": "^1.0.0",
    "webpack-dev-server": "^2.9.7"
  },
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon ./start.js"
  },
  "author": "*** ********",
  "license": "ISC",
  "dependencies": {
    "cookie-parser": "^1.4.3",
    "dotenv": "^4.0.0",
    "express": "^4.16.2",
    "mongod": "^2.0.0",
    "mongoose": "^4.13.7",
    "nodemon": "^1.14.1",
    "normalize.css": "^6.0.0"
  }
}

这是我的start.js文件:

const mongoose = require('mongoose');

// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });

mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise; 
mongoose.connection.on('error', (err) => {
  console.error(`${err.message}`);
});


const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});

这是我的app.js:

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const routes = require('./routes/index');
const errorHandlers = require('./handlers/errorHandlers');


const app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.use('/', routes);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// One of our error handlers will see if these errors are just validation errors
app.use(errorHandlers.flashValidationErrors);

// Otherwise this was a really bad error we didn't expect! Shoot eh
if (app.get('env') === 'development') {
  /* Development Error Handler - Prints stack trace */
  app.use(errorHandlers.developmentErrors);
}

// production error handler
app.use(errorHandlers.productionErrors);

module.exports = app;

这是我必须处理所有路由的index.js文件:

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  res.send('Hello World!');
});

module.exports = router;

当我在命令行上运行npm start时,我得到的是:

> summer_breeze@1.0.0 start /Users/**********/Repos/Summer_Breeze
> nodemon ./start.js

[nodemon] 1.14.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./start.js`
Express running → PORT 7777

哪个好。这正如我预期的那样运行。但是当我在网络浏览器中访问localhost:7777 /时,它会在我的公共文件夹中提取我的index.html页面,当我在开发工具中启动控制台时,什么都没有。这就好像它完全忽略了我创建的路线。

为什么会这样?我唯一的路线只是控制日志'Hello World!'。我以为我必须跑  router.get('/', (req, res) => { res.sendFile('public/index.html'); });要加载我的index.html文件。

为什么要拉我的index.html文件?如果在找到我的index.js文件时出现问题,是否存在为我的静态文件提供服务的默认路由?我甚至试图从我的index.js文件中删除所有路由,但它似乎仍然加载了我的index.html文件。

有谁能让我更深入地了解发生了什么?万分感谢!

2 个答案:

答案 0 :(得分:2)

尝试交换app.use(express.static(path.join(__dirname, 'public')));app.use('/', routes);

答案 1 :(得分:0)

res.send实际上是通过你传递的字符串发送一个响应。注释掉res.send并使用console.log(" hello world"),然后您将在服务器的控制台中看到它,因为它的服务器端。不是Chrome开发工具。