当运行带有express的节点时,在浏览器中显示“无法获取”错误

时间:2019-06-11 11:36:46

标签: javascript node.js express

我正在尝试制作一个单页应用程序,并且在后端部分中我已经有了代码,但是当我想与我的api邮递员进行检查并运行服务器时,我会得到一个错误

'use strict';

require('dotenv').config();
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const routes = require('./webserver/routes');
const mysqlPool = require('./ddbb/mysql-pool');


process.on("uncaughtException", err => {
    console.error("unexpected exception", err.message, err);
  });  

  process.on("unhandledRejection", err => {  
    console.error("unexpected error", err.message, err);  
  });

const app = express();
app.use(bodyParser.json());

app.use((err, req, res, next) => {
    console.error(err);
    res.status(400).send({
        error: `Body parser: ${err.message}`,
    });
});

/**

 * Enable CORS 

 */

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

app.use('/api', routes.accountRouter);
app.use('/api', routes.userRouter);

app.use((err, req, res, next) => {
    const { name: errorName } = err;  
    if (errorName === "AccountNotActivatedError") {  
      return res.status(403).send({  
        message: err.message  
      });  
    }  
    return res.status(500).send({  
      error: err.message  
    });  
  });

async function init() {
    try {
        await mysqlPool.connect();
    } catch(e) {
        console.error(e);
        process.exit(1);
    }
    const port = process.env.PORT;
    app.listen(port, () => {
        console.log(`Server running and listening on port ${port}`);
        });
}

init();

Visual Studio终端中的

告诉我服务器正在侦听并正在分配的端口上运行,但是在浏览器中却显示错误消息“无法获取”,邮递员无法连接我

1 个答案:

答案 0 :(得分:0)

您具有以/ api为前缀的路由,但没有根('/')的路由。 尝试使用:

app.get('/', function (req, res, next) {  
   //your code here
   res.send(200);
})