篇首语:本文由小编为大家整理,主要介绍了axios表单提交--vue.js相关的知识,希望对你有一定的参考价值。
一、首先这是对前端使用node开发
二、现在是 vue2 官方推荐 使用axios作为网络层,vue-resource 已经不再维护了。
axios 默认支持json提交数据,用OPTIONS来解决跨域。
但是这样后台接收数据需要定义单独的类来接受数据。
如果接受任何数据都需要单独定义一个类来接受的话就显得特别麻烦,
比如我们需要下面这样接受数据,就需要模拟表单来提交
public AdminUser login(AdminUser adminUser,String hello) throws NativeException return adminUserSerive.login(adminUser);
我们只需要简单的配置就可以了:
npm install qs -S
const instance = axios.create( headers: 'Content-Type': 'application/x-www-form-urlencoded' );
instance( method: type, url: url, data:qs.stringify(content) ).then((resp) => handleSuccess(resp, callback, errorBack); , (error) => handleError(errorBack); );
完整代码:
/** * Created by mangues on 2017/4/5. */ <script> import axios from 'axios'; import qs from 'qs'; import Notice from '../Notice'; const instance = axios.create( baseURL: process.env.API_ROOT, timeout: 20000, headers: 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' ); export default MgPost(url,content,callback,errorBack) var isLoading = arguments[arguments.length-1]; handleAjax(url,"post",content,callback,errorBack,isLoading); , MgGet(url,content,callback,errorBack,isLoading) var isLoading = arguments[arguments.length-1]; handleAjax(url,"get",content,callback,errorBack,isLoading); function handleAjax(url,type,content,callback,errorBack,isLoading) if (typeof isLoading != "boolean") //最后一位不是boolean if (typeof errorBack != 'function') //是函数 errorBack = function (data) if (data.code == -1) Notice.NoticeError("网络异常,请检查网络设置!"); else Notice.NoticeError(data.message); return instance( method: type, url: url, data:qs.stringify(content) ).then((resp) => handleSuccess(resp, callback, errorBack); , (error) => handleError(errorBack); ); function handleError(errorBack) var value = ; value.code = -1; value.message= "网络异常,请检查网络设置!"; errorBack(value); function handleSuccess(resp,callback,errorBack) var value = resp.data; var code = value.code; var message = value.message; var v = value.data; switch(code) case $financeinit.ResultCode.success://成功 callback(v); break; case $financeinit.ResultCode.un_login://未登录 if (confirm("登录失效,是否去登录?")) window.location.href = loginhtml; break; default: errorBack(value); break; </script>
以上是关于axios表单提交--vue.js的主要内容,如果未能解决你的问题,请参考以下文章