vue2.0-axios-post的使用,以及前后台跨域搭配

1.安装axois

2.main.js引入并配置

import axios from 'axios'
Vue.prototype.$ajax= axios
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = "http://xxxx.natapp1.cc/xm"

3.POST提交参数,POST提交参数的格式有严格要求,如果前后台搭配不当,就会出现问题。根据参数传递的数量,有两种POST的提交方式。

(1)POST参数少的时候

postTest(){
      //参数少
      var param = new URLSearchParams();
      param.append('emailAccount','xxx996537@qq.com');
      this.$ajax({
        method: 'post',
        url: '/v_register',
        data:param
      })
      .then(function(response){
        console.log(response.data)
        alert("post success!");
      })
      .catch(function(error){
        console.log(error);
      })

    }

此时对应的后端接收参数格式为:

 @PostMapping("/v_register")
 public Result v_register(String emailAccount){}

(2)POST参数多的时候

    //参数多 ,构造json:

      data{'id':'1','name':'小明'…}

      this.$ajax({
        method: 'post',
        url: '/v_register',
        data:data
      })
      .then(function(response){
        console.log(response.data)
        alert("post success!");
      })
      .catch(function(error){
        console.log(error);
      })

    },

此时对应的后端接收参数格式为:

 @PostMapping("/v_registers")

 public Result v_register(Object user){}

4.后端SpringBoot配置跨域

(1)将SpringBoot的版本调到2.0或者以下

(2)配置Config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


/**
 * @Auther: Chandler
 * @Date: 2018/6/11 15:43
 * @Description: 配置跨域
 */
@Configuration
public class CorsConfig{


private CorsConfiguration buildConfig() {  
        CorsConfiguration corsConfiguration = new CorsConfiguration();  
        corsConfiguration.addAllowedOrigin("*"); // 1  
        corsConfiguration.addAllowedHeader("*"); // 2  
        corsConfiguration.addAllowedMethod("*"); // 3  
        return corsConfiguration;  
    }  
  
    @Bean  
    public CorsFilter corsFilter() {  
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
        source.registerCorsConfiguration("/**", buildConfig()); // 4  
        return new CorsFilter(source);  
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值