- Axios是一个基于promise网络请求库,作用于node.js和浏览器中
- Axios在浏览器端使用XMLHttpRequests发送网络请求,并能自动完成json数据的转换
- 安装:npm install axios
跨域问题
- 同源:两个页面具有相同的协议(protocol),主机(host)和端口号(port)
- 为保证浏览器的安全,在没有授权的情况下,不允许不同源的脚本发送请求,cookie也不能共享
跨域问题解决
后端实现CORS接口
CORS将请求分为两类:简单请求和非简单请求
简单请求:
非简单请求:每次需要先发OPTION请求,获得授权,再发真正请求
@CrossOrigin
package com.example.onlineexams.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}