找不到合适的模拟服务器来提供具有预定义 url 的 json 响应



那么问题如下:

我正在开发一个前端应用程序(使用 vue.js(,我必须寻找一个模拟后端(我不能在前面模拟它(。

在这个应用程序中,我可以发出http请求,只有GET和PATCH符合我的兴趣,我想向模拟服务器发出这些请求(json:api兼容,这意味着它返回正确的内容类型标头作为application/vnd.api+json(。

该服务器必须使用预定义(已经硬编码(的 json 响应进行响应,所以我唯一关心服务器的是它会查看请求中的 url 并使用现有的 json 文件或对象进行响应。

我已经看到了一些解决方案,但没有一个可以配置要接收的 url 的解决方案,如下所示(我只关心方法和 url 是否匹配,我返回一个 json 文件(,例如:

  • 请求:(可以是mysite (dot( com或localhost:PORTNUMBER(
    GET http://localhost:PORTNUMBER/api/projects/1000?include=subtree,subtree.vertices,vertices

然后我用硬编码的 json 文件响应

与 Patch 相同,我实际上并不关心分析正文,只是使用 url 匹配来提供正确的预定义响应,这个没有造成问题,因为 url 要简单得多,我找到的解决方案支持这种类型的 url:

补丁 http://localhost:PORTNUMBER/api/projects/500

是否有任何解决方案可以将我的端点配置为 GET 请求的 url?我发现的那些给我抛出了一个不正确的路径错误,因为?包括...URL的一部分,因为它们仅作为路径/路径/资源提供东西,但是当涉及到路径/路径/资源时,任何奇怪的URL-I-need都会导致问题,到目前为止,我只需要一些"简单"的东西。

我自己使用node.js尝试了这个:

// app.js, my main file
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
// configuring the body parser to accept JSON as well as url encoded values
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({
type: ['application/json', 'application/vnd.api+json']
}));
var routes = require("./routes/routes.js")(app);
var server = app.listen(3000, function () {
console.log("Listening on port %s...", server.address().port);
});

在路由中,我定义它:

// inside /routes/routes.js
var appRouter = function(app) {
// only works if I let it like "api/projects/1000"
app.get("api/projects/1000?include=subtree,subtree.vertices,vertices",   function(req, res) {
res.set('Content-Type', 'application/vnd.api+json');
res.send({-----here goes my json response-----});
});
}
module.exports = appRouter;

设法做到了,然后我使用了:

app.get("api/projects/1000", function(req, res) {
res.set('Content-Type', 'application/vnd.api+json');
if(!req.query.include){
res.send(---whatever response when the url doesn't have include---)
return;
}
res.send({-----here goes my json response when it has include-----});
});

也许这不是世界上最好的事情,但从这里您可以将其设置为发送以前编写的 json 文件或您需要的任何内容,完全根据您的需要进行调整,如果有人有建议作为最佳回应,请随时发表评论:)

最新更新