在 REST API 表达式中顺序是否重要,即。获取 -> 发布 -> 放置 -> 删除?



如果你在另一个方法(例如post)之前实现 app.post())之前实现get方法,这有关系吗?我不确定为什么更改顺序会有意义,但是在我构建的快速应用程序中,如果我在get之前实现post,我的数据将缓冲然后每隔一次调用发布,发布不一致。当我切换顺序时,问题已解决。

这是请求的代码

const xhrPost = new XMLHttpRequest();
const xhrGet = new XMLHttpRequest();
//sends data to DB
xhrPost.open("POST", '/endgame', true);
xhrPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhrPost.send(JSON.stringify({
playerScore: score
}));
//when data is done being posted, get list of scores from db
xhrPost.onreadystatechange = function() {
console.log(this.responseText);
if (this.readyState === 4 && this.status === 200) {
xhrGet.open("GET", '/endgame', true);
xhrGet.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhrGet.send();
}
}
//when scores retrieved display results on console
xhrGet.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.table(JSON.parse(this.responseText));
var data = (JSON.parse(this.responseText));
ctx.fillText(data[0].playerScore, 50, 150);
}
};

这是服务器端代码

mongodb.MongoClient.connect(url, (error, database) => {
if (error) return process.exit(1)
const db = database.db('js-snake-scores')
app.post('/endgame', (req, res) => {
let score = req.body
db.collection('scores')
.insert(score, (error, results) => {
if (error) return
res.send(results)
})
})
app.get('/endgame', (req, res) => {
db.collection('scores')
.find({}, {
playerScore: 1
}).toArray((err, data) => {
if (err) return next(err)
res.send(data)
})
})
app.use(express.static(path.join(__dirname, 'static')))
app.listen(process.env.PORT || 5000)
})

如果你在另一个方法(例如post)之前实现 app.post())之前实现get方法,这有关系吗?

不。 仅当两个路由同时处理相同的路径和相同的方法时,顺序才重要。 因此,由于app.post()app.get()各自只拦截不同的方法,因此它们不会以任何方式竞争,因此它们之间的相对顺序无关紧要。 只有一个会在 GET 上触发,只有另一个会在 POST 上触发,无论它们的定义顺序如何。

如果您看到由于顺序而导致的行为差异,那么它一定是由于其他一些影响,而不仅仅是具有相同路径的app.get()app.post(),因为这两个永远不会在同一请求上激活。 如果我们可以看到两种代码实现,其中您说切换它们时顺序很重要,那么我们可能会为您提供更好的了解,说明为什么您会看到行为上的差异。app.post()app.get()单独排序不会导致您所描述的内容。

最新更新