这两天调试vue
和express
发现当我们使用axios
发送post
请求的时候,后台的req.body
一直为空,无法得到参数,然后根据网上查资料,添加'Content-Type': 'application/x-www-form-=urlencoded;charset=UTF-8',
这类的方法,但好像并没有什么卵用,然后在服务端用req.on("data",function(data){}
的方式才得以解决,现在将axios
的使用代码在这儿分享一下
解决方法1、application/x-www-form-=urlencoded;和req.on
http.js 这是一个工具类
'use strict'
import axios from "axios"
import qs from 'qs'
let axiosPreURl = "http://localhost:30001/";//配置全局的代理
axios.interceptors.request.use(config=>{//config包含每次请求的内容
if(localStorage.getItem('apt_token')){
config.headers.apiToken = `${localhostStorage.getItem('api_token')}`;
}
return config;
},err=>{
return Promise.reject(err);
});
axios.interceptors.response.use(response=>{
return response
},error => {
return Promise.resolve(error.response)
});
function checkStatus (response) {//检查状态码的方法
if (response && (response.status == 200 || response.status == 304 || response.status == 400)){
return response;
}
return {
status:-404,
msg:'网络异常'
}
}
function checkCode(response) {//如果失败,弹出错误信息
if (response.status === -404){
alert(response.msg);
}
return res;
}
export default {
post(url, data) {
return axios({
method:'post',
baseURL: axiosPreURl,
url,
data:qs.stringify(data),//序列化
timeout:5000,
headers:{
'X-Requested-With':'XMLHttpRequest',
'Content-Type': 'application/x-www-form-=urlencoded;charset=UTF-8',
}
}).then(
(response) => {//不管成功还是失败都会有这两次的过滤,筛选错误信息
return checkStatus(response)
}
).then(
(res) => {//如果失败
return checkCode(res)
}
)
},
get(url,params){
return axios({
method:'get',
baseURL:axiosPreURl,
url: url,
params,
timeout:5000,
headers:{
'x-Requested-With':'XMLHttpRequest'
}
}).then(
(response) =>{
return checkStatus(response);
}
).then(
(res)=>{
return checkCode(res)
}
)
}
}
main.js主线程中用这个方法加载
import axios from './utils/http.js';
...
...
Vue.prototype.$axios = axios;
vue的具体方法中使用方式:
self.$axios.post("/test.do",{"baipu":"白璞"})
.then(
(data)=>{
console.log(data);
}
)
服务端的使用:
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));//这两个是和post请求有关系的
app.use(express.urlencoded({ extended: false }));//这个是和get又关系的
var express = require('express');
var querystring = require("querystring");
var router = express.Router();
var fs = require('fs');
router.post("/test.do",function (req,res,next) {//正常补货到一个文件
console.log(req.body);//body拿到的数据是{}空的
req.on("data",function(data){//监听数据过来
console.log(decodeURIComponent(data));//转码
var param = querystring.parse(decodeURIComponent(data));//转成object对象,方便使用
var data = fs.readFileSync('./data/getLinks.json', 'utf8');//读取本地的一个文件
var data = JSON.parse(data);//序列化
res.send(data);//返回去
});
});
以上是一条解决方法,
解决方法二:application/json 和req.body
但是当我们把上传方法改一下,http.js 中的 post 方法如下:
post(url, data) {
return axios({
method:'post',
baseURL: axiosPreURl,
url,
data,//这里直接进行赋值,不进行转化
timeout:5000,
headers:{
'X-Requested-With':'XMLHttpRequest',
'Content-Type': 'application/json',//这里以json的格式上传文件
}
})
express 服务端将看到:
console.log(req.body);//这里能够拿到参数
req.on("data",function(data){//监听数据过来
console.log(" i am in req.on 方法");
});
网友评论