代码之家  ›  专栏  ›  技术社区  ›  newman

节点。js+Express路线未按预期工作

  •  0
  • newman  · 技术社区  · 7 年前

    我对Node还不太熟悉。js和我对连接本地主机和与MongoDB的接口感到有些困惑。似乎它忽略了我创建的路线。

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

    enter image description here

    这是我的包裹。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"
      }
    }
    

    这是我的开始。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}`);
    });
    

    这是我的应用程序。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;
    

    这是索引。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
    

    这很好。这是我所期待的。但当我在web浏览器中转到localhost:7777时,它会调出我的索引。公共文件夹中的html页面,当我在开发工具中打开控制台时,什么都没有。这就好像完全忽略了我创建的路线。

    为什么会这样?我唯一的路径应该是控制台日志“Hello World!”。我以为我得跑了 router.get('/', (req, res) => { res.sendFile('public/index.html'); }); 让它加载我的索引。html文件。

    为什么它会拉我的索引。html文件?如果在查找索引时出现问题,是否有一个默认路由为静态文件提供服务。js文件?我甚至尝试从索引中删除所有路由。js文件,它似乎仍在加载我的索引。html文件。

    有谁能让我更深入地了解一下正在发生的事情吗?非常感谢!

    2 回复  |  直到 7 年前
        1
  •  3
  •   Vasyl Moskalov    7 年前

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

        2
  •  0
  •   arrra    7 年前

    res.send实际上是用您传递的字符串发送响应。注释掉res.send并使用控制台。日志(“hello world”),然后您将在服务器的控制台中看到它,因为它是服务器端的。不在chrome开发工具上。