Express

时间:2017-08-28 03:44:47

标签: node.js express

我正在学习Express on Node并运行一个简单的服务器脚本,如果它作为变量提供,应该返回你的名字,但我不知道如何在URL中调用变量

http://localhost:3000/:$jon
http://localhost:3000/?jon
http://localhost:3000/$jon
http://localhost:3000/:$jon
http://localhost:3000/:([\$])$jon

我真的认为这只是......

http://localhost:3000/jon

目录中只有2个文件是server.js

// Load the 'express' module
const express = require('express');

// Create a new Express application instance
const app = express();

// Create a new 'hasName' middleware function
const hasName = function(req, res, next) {
    // Use the QueryString 'name' parameter to decide on a proper response
    if (req.param('name')) {
        // If a 'name' parameter exists it will call the next middleware
        next();
    } else {
        // If a 'name' parameter does not exists it will return a proper response 
        res.send('What is you name?');
    }
};

// Create a new 'sayHello' middleware function
const sayHello = function(req, res, next) {
    // Use the 'response' object to send a respone with the 'name' parameter 
    res.send('Hello ' + req.param('name'));
};

// Mount both middleware funcitons
app.get('/', hasName, sayHello);

// Use the Express application instance to listen to the '3000' port
app.listen(3000);

// Log the server status to the console
console.log('Server running at http://localhost:3000/');

// Use the module.exports property to expose our Express application instance for external usage
module.exports = app;

然后将package.json包含在express

{
    "name": "MEAN",
    "version": "0.0.3",
    "dependencies": {
        "express": "4.14.0"
    }
}

我正在运行nmp install来安装依赖项中的表达式,然后node server然后获取我在localhost上所期望的内容

enter image description here

但我也注意到我在第10行得到了折旧..所以我说错了或者我需要修补这个文件吗?这是一本最近出版的书。

params deprecated

2 个答案:

答案 0 :(得分:1)

使用req.params.name代替

https://expressjs.com/en/4x/api.html#req.params

你可以用这种方式编写代码:

const express = require('express');
const app = express();
app.get('/', function(req, res, next){
  res.send("what's your name?");
});

app.get('/:name', function(req, res, next){
  res.send('Hello ' + req.params.name);
});

app.listen(3000, function(){
  console.log('Server running at http://localhost:3000/');
});

答案 1 :(得分:1)

您可以使用app.get('/:name', hasName, sayHello);代替app.get('/', hasName, sayHello);