什么是跨域

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

跨域错误示例

image-20220812144533497

如何解决

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;

/**
* @Author: 羡羡
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 跨域
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
//所有
registry.addMapping("/**")
//支持的方法
/*.allowedOrigins("*")*/
.allowedOriginPatterns("*")
//支持的方法
.allowedMethods("GET","PUT","DELETE","POST","HEAD","OPTIONS")
//证书
.allowCredentials(true)
//超时
.maxAge(3600)
//允许头
.allowedHeaders("*");
}
}

NodeJS解决

下载依赖

本实例以Express框架为例

npm i cors

配置app.js

const cors=require('cors');

app.use(cors());

前端解决

配置vue.config.js

devServer: {
proxy:"http://127.0.0.1:8090",//接口的地址
port: 8080 //本地运行端口 默认8080
}

axios请求

后台

/**
* 获取文章 且 分页
* @param pagenum 当前页
* @param pagesize 每页的数量
* @return
*/
@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请求
//后台接口地址:http://localhost:8090/article?pagesize=10
this.$http.get('/article?pagesize=10').then((res)=>{
console.log(res);
})
POST请求
//后台接口地址:http://localhost:8090/artce  需要带参数ok
this.$http.post('/artce',{
ok:10
}).then((res)=>{
console.log(res);
})