当前位置:网站首页>NodeJS使用Express框架进行POST请求报“BadRequestError:request aborted”
NodeJS使用Express框架进行POST请求报“BadRequestError:request aborted”
2022-07-21 17:35:00 【森之千手】
先上报错图:
直接说结果吧,跟你是否启用了mock.js有关。
由于我的前端框架采用了VueElementAdmin,这个框架内置了mockJS的模拟数据。所以我默认也采用了这个配置。
前端采用的是axios作为请求框架,关键代码如下:
import axios from 'axios'
// 创建axios实例
const service = axios.create({
baseURL: 'http://127.0.0.1:95', // url = base url + request url
withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
export default service
主要的后端代码如下:
const express = require('express')
const server = express()
const startServer = () => {
server.use(express.json())
server.use(express.urlencoded({ extended: true }))
server.post('/home/login', (req, resp) => {
console.log(req.query)
resp.send({
code: 200
})
})
const { port, hostName } = $serverConfig
server.listen(port, hostName, () => {
console.log(`服务已经启动:http://${ hostName }:${ port }`)
})
}
另外,因为要解决跨域问题,前端使用了代理:
'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
function resolve(dir) {
return path.join(__dirname, dir)
}
const name = defaultSettings.title || 'vue Admin Template' // page title
const port = process.env.VUE_APP_PORT
const baseApi = process.env.VUE_APP_BASE_API
const targetApi = process.env.VUE_APP_TARGET_API
const pathRewrite = process.env.VUE_APP_REWRITE_PATH
module.exports = {
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV !== 'production',
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {
[baseApi]: {
target: targetApi,
changeOrigin: true,
pathRewrite: {
['^' + baseApi]: pathRewrite
}
}
},
before: require('./mock/mock-server.js')
}
}
# just a flag
ENV = 'development'
VUE_APP_ENV='development'
# base api
VUE_APP_BASE_API = '/dev-api'
VUE_APP_REWRITE_PATH = ''
# 页面服务端口
VUE_APP_PORT = 4310
# 目标转发地址
VUE_APP_TARGET_API='http://127.0.0.1:95'
分析
axios默认的header里面的content-type就是application/json。然后后端的解析也是json形式。可是采用了这个mockJS的mock-server后改变了传输形式,导致不能识别。解决办法也很简单,在axios创建的时候指定header的content-type:
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
withCredentials: true, // send cookies when cross-domain requests
timeout: 5000, // request timeout
headers: {
'Content-Type': 'application/json; charset=UTF-8;'
}
})
然后express那边可以不用配接收的header,默认是识别content-type的,当然配置也可以,可以使用下面的模板,增加中间件:
server.all("*", function (req, res, next) {
//设置允许跨域的域名,*代表允许任意域名跨域
res.header("Access-Control-Allow-Origin", "*")
//允许的header类型
res.header("Access-Control-Allow-Headers", "*")
//跨域允许的请求方式
res.header("Access-Control-Allow-Methods", "*")
res.header("Access-Control-Allow-Credentials", "true")
if (req.method.toLowerCase() == 'options') {
res.send(200) //让options尝试请求快速结束
} else {
next()
}
比较暴力,全部放开。当然,可以按需更改。
边栏推荐
- leetcode_两数相加_个人解法
- Hisilicon [hi3531]onvif protocol is implemented based on gSOAP and OpenSSL_ Code article
- JS时间和时间戳的转换
- 序列化和反序列化
- Quantitative transaction Diary - summary in February 2021
- 解决IDEA的插件中心连接不上网络
- 多线程与线程池
- Vscode add custom comment
- Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions.
- 三星6818基于uboot的流水灯程序
猜你喜欢
OSPF routing control
Experimental support for decorators is a feature that is subject to change in a future release. Set
Quantify three types of market in trading
QML drag pictures and objects across windows
指针深度解刨《三》(数组的认知)
Vscode configuration code automatic formatting and repair
Dynamic memory management
[C language] document operation "I"
OpenGL贴图保持原比例的一种方法
鼠标移入select options会触发mouseleave 事件处理方案
随机推荐
类的加载机制以及双亲委托机制
Typo in static class property declarationeslint
一种图片选择自定义控件
v-7
Quantify three types of market in trading
指针的深度解刨《七》(函数指针相关知识)
海思Hi3531||瑞芯微RK1109用rtsp服务器实现h264推流
Hisilicon hi3531 | Ruixin micro rk1109 realizes H264 streaming with RTSP server
Must use destructuring props assignmenteslint
Cannot read property ‘type‘ of undefined Occurred while linting **\index. jsx:1
命令行编辑的快捷键,以及操作技巧命令
Hisilicon [hi3531]gpio lighting application and register operation
Token
RK3288关于LVDS信号配置和1080p视频信号的详解
Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions.
Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions.
C textbox password box setting
IO 模型详解(通俗易懂)
ts 学习记录(一)sudo忘记密码(乌龙)Try changing the ‘lib’ compiler option to include ‘dom’.
2021-09-23