首页 > 解决方案 > 回调的优先级,如何使用 node express js 处理 xmlhttprequest 发布请求

问题描述

我在管理 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 发布请求,它应该必须得到 app.post 的响应声明,鄙视他之前调用的 app.use 声明。

标签: javascriptnode.jsexpressweb

解决方案


您的代码应该是

app.get("/", (request, response) => {

  console.log("inside app.use")

  response.sendFile(path.join(__dirname, "index.html"))


})

app.get / app.post 是定义路由。而 app.use 是附加中间件。


推荐阅读