写一个vue跨域到springboot的事例项目
时间: 2023-12-18 07:02:56 浏览: 31
好的,我给您提供一个简单的 Vue 和 Spring Boot 的跨域请求示例项目。
1. 首先,我们需要创建一个 Spring Boot 项目,可以使用 Spring Initializr 快速创建一个空的 Maven 项目,然后添加以下依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
2. 然后,创建一个简单的 RESTful 接口,用于处理跨域请求:
```java
@RestController
@RequestMapping("/api")
public class MyController {
@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
```
在上面的代码中,`@CrossOrigin` 注解的 `origins` 属性设置为 `http://localhost:8080`,表示允许来自该域名的请求访问该接口。
3. 接着,我们需要创建一个简单的 Vue 项目,使用 Vue CLI 快速创建一个空的项目,然后在 `App.vue` 中添加以下代码:
```vue
<template>
<div>
<button @click="getData">获取数据</button>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
},
methods: {
getData() {
fetch('http://localhost:8080/api/hello')
.then(response => response.text())
.then(data => {
this.message = data
})
.catch(error => {
console.error('请求失败:', error)
})
}
}
}
</script>
```
在上面的代码中,我们使用 `fetch` 函数向 Spring Boot 项目发送 GET 请求,获取 `/api/hello` 接口返回的数据,并将数据显示在页面上。
4. 最后,在 Spring Boot 项目的 `application.properties` 文件中,添加以下配置来解决跨域问题:
```
spring.mvc.cors.allowed-origins=http://localhost:8081
```
上面的配置表示允许来自 `http://localhost:8081` 域名的请求访问该接口。
5. 启动 Spring Boot 项目和 Vue 项目,在浏览器中访问 `http://localhost:8081`,点击“获取数据”按钮,可以看到页面上显示了“Hello, world!”。
以上就是一个简单的 Vue 和 Spring Boot 的跨域请求示例项目。