后端
package com.pp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
public class TestController {
// 欢迎页面
@RequestMapping("/test2")
@ResponseBody
public Map test() {
Map<String,String> map = new HashMap<String, String>();
map.put("测试1","123");
map.put("测试2","456");
return map;
}
}
允许跨域配置类
package com.pp.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
@Override
protected void addCorsMappings(CorsRegistry registry) {
System.out.println("----------------------");
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
前端页面
在项目根目录创建一个 vue.config.js文件,可进行baseUrl配置,接口代理以及其他配置
(vue-cli3没有bulid和config文件夹)
module.exports = {
devServer: {
proxy: {
// 配置跨域
'/api': { //代理接口前缀为/api的请求
target: 'http://localhost:7007', //需要代理到的目标地址
ws: true,
changOrigin: true, //是否跨域
pathRewrite: {
'^/api': '' //重写路径
}
}
}
}
};
https://blog.csdn.net/lihefei_coder/article/details/97630544
https://blog.csdn.net/weixin_38578293/article/details/84823027
<template>
<div class="info">
这是从本地后端项目获取的json数据:
<button v-on:click="postInfo">获取数据</button>
<br>
{{this.info}}
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
info: {}
}
},
methods: {
postInfo: function () {
this.$http.post('/api/test2')
.then(response => (this.info = response))
.catch(function (error) { // 请求失败处理
// eslint-disable-next-line no-console
console.log(error);
});
}
}
}
</script>
<style>
.info{
width:100%;
height: 100%;
}
</style>
在main.js中:
Vue.prototype.$http = axios
所以是
this.$http.post('/api/test2')
调用结果: