API字符串未通过Express中的console.log传递

时间:2019-08-03 13:19:38

标签: node.js express

我正在做Express crash course,而我的第一个线索是我跑步

app.listen(PORT, () => console.log('Server started on port ${PORT}'));  

,它没有传递端口号。问题仍然存在于此区域,它只会使服务器崩溃:

const logger = (req, res, next) =>{
console.log('${req.protocol}://${req.get('host')}${req.originalUrl}');
next();
};

现在,这是完整的index.js:

const express = require('express');
const path = require('path');
const members = require('./Members');
const app = express();

const logger = (req, res, next) =>{
console.log('${req.protocol}://${req.get('host')}${req.originalUrl}');
next();
};

app.use(logger);

app.get('/api/members', (req, res)=> {
res.json(members);

});

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

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log('Server started on port ${PORT}')); 

错误:

   console.log('${req.protocol}://${req.get('host')}${req.originalUrl}');
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: missing ) after argument list
        at Module._compile (internal/modules/cjs/loader.js:723:23)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
        at Module.load (internal/modules/cjs/loader.js:653:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
        at Function.Module._load (internal/modules/cjs/loader.js:585:3)
        at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
        at startup (internal/bootstrap/node.js:283:19)
        at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

2 个答案:

答案 0 :(得分:1)

Template strings确实要使用反引号:

  

模板文字用反引号(``)括起来

因此

vmci://

应该是

console.log('${req.protocol}://${req.get('host')}${req.originalUrl}');

console.log(`${req.protocol}://${req.get('host')}${req.originalUrl}`);

应该是

app.listen(PORT, () => console.log('Server started on port ${PORT}'));  

答案 1 :(得分:0)

这是因为您使用的是'',它是一个仲裁字符串...要显示的端口,请使用''