URL中的空请求参数让我无法找到API错误
我的代码是:
xyz.js
const testFunction = (req, res) => {
req.checkParams('xyz_name', 'Invalid name').notEmpty();
req.sanitize('xyz_name').trim();
const errors = req.validationErrors();
if (errors) {
res.json({
status: '500',
message: errors
});
} else {
res.json({
status: '200',
message: 'list',
data: req.params.xyz_name
});
}
};
module.exports = testFunction;
app.js
app.get('/test/xyz/:xyz_name', test);
当我尝试http://localhost:3000/test/xyz/abc
时,它工作正常。但是当我输入http://localhost:3000/test/xyz
时,它会给我错误
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /test/xyz</pre>
</body>
有没有什么,我在我的代码中缺少使它工作?
回答如下:如果Express.js中有可选参数,则需要使用?
指定它。
/test/xyz/:xyz_name
将匹配/test/xyz/test
但不匹配/test/xyz
。这基本上是将xyz_name
设置为必需参数。如果没有提供任何东西,它将失败。
而/test/xyz/:xyz_name?
将匹配/test/xyz/test
和/test/xyz
。这是将xyz_name
设置为可选参数。如果没有提供任何东西,路线仍将被击中。
URL中的空请求参数让我无法找到API错误
我的代码是:
xyz.js
const testFunction = (req, res) => {
req.checkParams('xyz_name', 'Invalid name').notEmpty();
req.sanitize('xyz_name').trim();
const errors = req.validationErrors();
if (errors) {
res.json({
status: '500',
message: errors
});
} else {
res.json({
status: '200',
message: 'list',
data: req.params.xyz_name
});
}
};
module.exports = testFunction;
app.js
app.get('/test/xyz/:xyz_name', test);
当我尝试http://localhost:3000/test/xyz/abc
时,它工作正常。但是当我输入http://localhost:3000/test/xyz
时,它会给我错误
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /test/xyz</pre>
</body>
有没有什么,我在我的代码中缺少使它工作?
回答如下:如果Express.js中有可选参数,则需要使用?
指定它。
/test/xyz/:xyz_name
将匹配/test/xyz/test
但不匹配/test/xyz
。这基本上是将xyz_name
设置为必需参数。如果没有提供任何东西,它将失败。
而/test/xyz/:xyz_name?
将匹配/test/xyz/test
和/test/xyz
。这是将xyz_name
设置为可选参数。如果没有提供任何东西,路线仍将被击中。