javascript - 回调的优先级,如何使用 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 声明。
解决方案
您的代码应该是
app.get("/", (request, response) => {
console.log("inside app.use")
response.sendFile(path.join(__dirname, "index.html"))
})
app.get / app.post 是定义路由。而 app.use 是附加中间件。
推荐阅读
- mysql - Mysql工作台逆向工程
- javascript - 如何在 React 中更新我的帖子的评论
- bash - 删除 bash 中最后一次出现的字符串
- eclipse - HANA Eclipse - 项目资源管理器“没有连接到数据库”
- javascript - 如何在 Cypress 中测试 Slate JS 行为
- php - 如何在 PHP 数组中找到填充的索引?
- python - 使用 mypy 时在 python 中正确键入异常/错误元组
- html - 为什么在使用“padding: 10px;!imprtant;”时我的导航栏上没有颜色
- webpack - Webpack 无法解析相对于包路径的模块
- git - Git - 多个遥控器是否可以有多个 .gitignore?