后端在本地运行地址是localhost:8080,前端也在本地运行,要怎么请求后端接口(学习笔记)
前端请求方法:
load () {
console.log('load加载数据列表')
// 发起 GET 请求
axios.get('http://localhost:8080/carbon')
.then(function (response) {
// 请求成功时处理
console.log(response.data)
})
.catch(function (error) {
// 请求失败时处理
console.log('请求失败')
console.log(error.message)
console.log(error)
})
},
在apipost中请求后端只需要发送GET请求 localhost:8080/carbon,前端请求浏览器报错:
已拦截跨源请求:同源策略禁止读取位于 http://localhost:8080/carbon 的远程资源。(原因:CORS 头缺少 ‘Access-Control-Allow-Origin’)。状态码:200
错误表明您的前端应用试图从 http://localhost:8080/carbon
获取资源,但由于跨源资源共享(CORS)策略的限制,请求被浏览器拦截了。尽管您收到了一个状态码为 200 的响应,这意味着服务器实际上成功地处理了请求并返回了数据,但浏览器因为缺少适当的 CORS 头而不会将响应数据暴露给前端 JavaScript 代码。
解决方法:在 Spring Boot 中,可以使用 @CrossOrigin
注解在方法或类级别上启用 CORS。这个注解可以放在 Controller 类或方法上。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://localhost:8081") // 前端启动后运行的地址
@GetMapping("/carbon")
public String carbon() {
return "Carbon Data";
}
}