如果你在app.get()之前的另一个方法(如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)
})
答案 0 :(得分:0)
如果你在另一个方法之前实现get方法,例如在app.get()之前实现app.post(),那么它是否重要?
没有。仅当两条路线同时处理相同路径和相同方法时,顺序才有意义。因此,由于app.post()
和app.get()
每个只拦截不同的方法,因此它们不会以任何方式竞争,因此它们之间的相对排序无关紧要。只有一个将在GET上触发,只有另一个将在POST上触发,无论它们的定义顺序如何。
如果您看到由于订单导致的行为差异,那么除了只有app.get()
和app.post()
之外,它必定是由于其他一些影响而具有相同路径,因为这两者不是在同一请求上激活。如果我们可以看到代码的两个实现,当您在切换它们时说顺序很重要,那么我们可能会让您更好地了解为什么看到行为上的差异。 app.post()
和app.get()
自行排序不会导致您所描述的内容。