iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue中post请求报400的解决方案
  • 316
分享到

vue中post请求报400的解决方案

vue中post请求post请求报400vue post请求报400 2022-11-13 18:11:02 316人浏览 八月长安
摘要

目录Vue post请求报400vue 异步请求问题1. get 请求方式2. post 请求方式3. axiOS 全局设置4. 请求代理vue post请求报400 1、为默认数据

vue post请求报400

1、为默认数据格式为JSON,发请求时参数报错

通过以下方式修改数据格式即可

import qs from 'qs';
// import qs from 'querystring'
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-fORM-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

2、检查发送的数据格式是否与后端要求相匹配,要求字符串,发送了数组也可能会出现400错误

vue 异步请求问题

Vue 中使用 axios 进行网络请求,使用起来和 Jquery 中的 $.get 和 $.post 功能类似。

安装依赖:cnpm install --save axios

1. get 请求方式

给定服务器控制器代码,可以接收 name 和 age 参数,设置到 Map 中并返回。

注意:控制器上有跨域注解。前后端分离都是跨域请求。且端口不能设置 8080 端口,避免端口冲突。

<template>
    <div id="app">
        <div>用户名:{{stu.name}}</div>
        <div>年龄:{{stu.age}}</div>
    </div>
</template>
<script>
    import axios from "axios"
    export default {
        name: 'App',
        data(){
            return{
                stu:{
                    "name":null,
                    "age":null,
                }
            }
        },
        mounted(){
            //页面加载事件
            axios.get("Http://localhost:8181/index?name=zhangsan&age=18")
                .then(res => {
                    console.log(res.data);
                    this.stu = res.data;
                })
                .catch(error => {
                    console.log(error);
                })
        }
    }
</script>

2. post 请求方式

POST 也支持 URL 重写方式传参,即通过 ? 和 & 传递参数,如果使用这种方式传参必须要结合 querystring 使用。

<template>
    <div id="app">
        发起请求获取到的结果:<span>{{name}},{{age}}</span>
    </div>
    <router-view/>
</template>
<script>
    import axios from "axios"
    import qstring from "querystring"
    export default {
        name: 'App',
        data(){
            return{
                name:null,
                age: null,
            }
        },
        mounted(){
            // 页面加载事件
            axios.post("http://localhost:8181/index", qstring.stringify({
                    name : "张三",
                    age: 23
            })) //处理的结果是 name=张三&age=23
            .then(res => {
                console.log(res.data);
                this.name = res.data.name;
                this.age = res.data.age;
            })
            .catch(error => {
                console.log(error);
            })
        }
    }
</script>

后端的业务代码:

@RestController
@CrossOrigin  //跨域注解
public class TestController {
    @RequestMapping("/index")
    public Map<String, Object> index(@Param("name") String name,@Param("age") Integer age){
        Map<String, Object> result = new HashMap<>();
        result.put("name", name);
        result.put("age", age);
        return result;
    }
}

3. axios 全局设置

如果使用上面的这种方式,需要在每个页面中都导入 axios,更简便的方式是全局绑定 axios。

修改 main.js

import { createApp } from 'vue'
import App from './App.vue'
//导入./router/index文件里面配置好的路由
import router from './router/index'
import axios from "axios"
import qstring from "querystring"
//全局Vue对象
const Vue=createApp(App);
// 设置axios、qstring全局
Vue.config.globalProperties.$axios=axios;
Vue.config.globalProperties.$qstring=qstring;
Vue.use(router).mount('#app');

页面中的写法:在任何页面中都可以直接使用 this.$axios 和 this.$qstring 进行设置。

<template>
    <div id="app">
        发起请求获取到的结果:<span>{{name}},{{age}}</span>
    </div>
    <router-view/>
</template>
<script>
    export default {
        name: 'App',
        data(){
            return{
                name:null,
                age: null,
            }
        },
        mounted(){
            // 页面加载事件
            this.$axios.post("/api/index", this.$qstring.stringify({
                    name: "张三",
                    age: 15
            }))
            .then(res => {
                console.log(res.data);
                this.name = res.data.name;
                this.age = res.data.age;
            })
            .catch(error => {
                console.log(error);
            })
        }
    }
</script>

4. 请求代理

在 Vue 中发起网络请求时 URL 都使用的是完整的 URL,可以把公共 URL 提出来,提出后发起网络请求时,URL 只写路径部分,省略协议、IP 和端口。

如果没有请求代理,每次在浏览器开发工具看见真实请求服务器地址,这样话就把服务器暴露给客户端了。使用代理后只能看见代理前请求,保护真实服务器地址。

项目根路径(不是src)下新建 vue.config.js:

这个配置文件操作完成后必须重启

const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
    transpileDependencies: true,
    lintOnSave:false,
    //配置请求代理
    devServer: {
        proxy: {
            //当请求Vue项目路径都以/api开头时,转发给下面
            '/api': {
                //服务器URL
                target: "http://localhost:8181/",
                ws: true,
                pathRewrite: {
                    //把路径中的api去掉
                    '^/api': ''
                },
                changeOrigin: true
            }
        }
    }
});

发起请求时可以使用 /api/xxx 的形式:

mounted(){
    // //页面加载事件
    axios.get("/api/index?name=zhangsan&age=18")
        .then(res => {
        console.log(res.data);
        this.name = res.data.name;
        this.age = res.data.age;
    })
        .catch(error => {
        console.log(error);
    })
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: vue中post请求报400的解决方案

本文链接: https://www.lsjlt.com/news/169171.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作