我正在尝试实现“ / userdata”路由:
api的理想响应如下:
出现错误时,显示以下响应-
{error: true, status: 403, userMessage: 'some query parameter missing',
data: <Name of the parameter that is missing>}.
必填的查询参数是-name:String,age:Number
成功后,显示以下响应-
{error: false, status: 200, userMessage: 'all query parameters entered',
data: {name: <Name passed in query params>, age: <age passed in query params>}}.
我几乎完成了实施,但是我想执行 数据类型检查中传递的参数。您能否建议是否有达到相同目标的方法?
我也尝试过使用req.params,而不是req.query。但是,这没有给我想要的输出。
// All code files
<app.js code>
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const response = require('./user-middleware');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Creating a route named query
app.get('/userdata',(req,res) => {
var name = req.query.name;
var age = req.query.age;
if(name === null || name === undefined || name.length === 0)
{
let apiResponse = response.generate(true, 403, 'some query parameter missing', {name:"name",age:`${age}`});
res.send(apiResponse);
}
else if(age === null || age === undefined || age.length===0)
{
let apiResponse = response.generate(true, 403, 'some query parameter missing', {name:`${name}`,age:"age"});
res.send(apiResponse);
}
else
{
let apiResponse = response.generate(false, 200, 'all query parameters entered', req.query);
res.send(apiResponse);
}
});
app.listen(3000);
module.exports = app;
<user-middleware.js code>
let generate = (error, status, userstatus, data) => {
let response = {
error: error,
status: status,
userstatus: userstatus,
data: data
};
return response;
};
module.exports = {
generate: generate
};
当前的响应如下:
如果仅传递名称:
http://localhost:3000/userdata?name=ace
输出:
{"error":true,"status":403,"userstatus":"some query parameter missing","data":{"name":"ace","age":"age"}}
如果仅通过年龄:
http://localhost:3000/userdata?age=21
输出:
{"error":true,"status":403,"userstatus":"some query parameter missing","data":{"name":"name","age":"21"}}
如果两个都通过了:
输出:
http://localhost:3000/userdata?name=ace&age=21
{"error":false,"status":200,"userstatus":"all query parameters entered","data":{"name":"ace","age":"21"}}
我想避免以下输出:
{"error":false,"status":200,"userstatus":"all query parameters entered","data":{"name":"21","age":"ace"}}
访问以下URL时:
http://localhost:3000/userdata?name=21&age=ace
由于数据类型已交换,因此不应将其视为理想的输出。
请让我知道是否可以实施上述方法?