[英]priority of calbacks, how to handle a xmlhttprequest post request with node express js
我在管理 xmlhttprequest 發布請求時遇到問題。 這是節點快遞服務器的代碼:
const fs = require("fs")
const path = require("path")
const express = require("express")
const app = express()
const port = 3001
app.use(express.static(__dirname))
app.use("/", (request, response) => {
console.log("inside app.use")
response.sendFile(path.join(__dirname, "index.html"))
})
app.post("/database", (request, response) => {
console.log("inside app.use02")
console.log("request-body: "+request)
console.log("response-body: "+response)
response.send("it works")
})
app.listen(port)
問題是當我向 /database url 發出 ajax 請求時,它由 app.use 語句而不是 app.post 語句提供。 這是為什么? 我不了解 expressjs 是如何工作的,它是什么?
const btnForm = document.getElementById("form-btn")
const input01 = document.getElementById("firstName")
const input02 = document.getElementById("lastName")
const input03 = document.getElementById("profession")
const form = document.getElementById("form01")
form.addEventListener("submit", sendForm)
const httprequest = new XMLHttpRequest()
const FD = new FormData()
function sendForm(event){
event.preventDefault()
console.log("sendForm")
FD.append(input01.name, input01.value)
FD.append(input02.name, input02.value)
FD.append(input03.name, input03.value)
httprequest.open("POST", "http://localhost:3001/database")
httprequest.send(FD)
}
我想知道的是為什么 ajax 請求首先由 app.use 語句而不是 app.post 語句提供,我認為既然我在做一個 ajax post 請求,它應該得到 app.post 的響應語句,鄙視他之前調用的app.use語句。
你的代碼應該是
app.get("/", (request, response) => {
console.log("inside app.use")
response.sendFile(path.join(__dirname, "index.html"))
})
app.get / app.post 是定義路由。 而 app.use 則是附加中間件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.