axios发送post请求,服务器拿不到参数的解决办法

这两天调试vueexpress发现当我们使用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 方法");
    });
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值