如何发送相对于发送响应的路由器的Location头?

时间:2015-10-07 23:10:55

标签: express

我有一个express应用,可以在某个路径上链接router。其中一个路由router,我们称之为commands,可以创建一个文档。创建该文档后,我想发回201状态和Location标题,其中包含已创建文档的位置,可在commands路由中的某处访问。

有没有办法相对于发送响应的router发送回此创建文档的位置?我不想硬编码。

Server.js

app.use("/commands", require("./routes/commands"));

commands.js

// Have a create route to create documents somewhere in the commands router
router.get("/create", function (req, res) {
    // Figure out what id were going to give our new document
    var documentIdToCreate = nextDocumentId;

    // Create the new document
    documents[documentIdToCreate] = new Document();

    // Increment the document id
    nextDocumentId = nextDocumentId + 1;

    // Set "Created" status
    res.status(201);

    /*
    Set the location of the created document.  I would think
    that express would have some mechanism for the router to
    locate itself either by doing some sort of path.resolve
    type method.
    */
    res.location(util.format("/%s", documentIdToCreate));

    // End the response
    res.send();
});

最后,我希望能够通过执行res.location(router.relativeContextPath() + "/" + someDocumentId);之类的操作来发送回位置,因为我必须发回res.location("/commands/" + someDocumentId);

1 个答案:

答案 0 :(得分:3)

我相信router.mountpathdocs here)和/或req.baseUrldocs here)可以解决问题。