什么是跨域
指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制
跨域错误示例

如何解决
springboot后端解决
package com.example.speedkill.config;
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration public class WebConfig implements WebMvcConfigurer {
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET","PUT","DELETE","POST","HEAD","OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }
|
NodeJS解决
下载依赖
配置app.js
const cors=require('cors');
app.use(cors());
|
前端解决
配置vue.config.js
devServer: { proxy:"http://127.0.0.1:8090", port: 8080 }
|
axios请求
后台
@RequestMapping(path = "/article",method = RequestMethod.GET) public JsonResult article(@RequestParam(defaultValue = "1") int pagenum,int pagesize){ return sysarservice.articleall(pagenum,pagesize); }
@RequestMapping(path = "/artce",method = RequestMethod.POST) public JsonResult ar (String ok){ return new JsonResult(200,"成功"); }
|
GET请求
this.$http.get('/article?pagesize=10').then((res)=>{ console.log(res); })
|
POST请求
this.$http.post('/artce',{ ok:10 }).then((res)=>{ console.log(res); })
|