axios請求到了數據但then返回不到數據,這是由於vue前端訪問地址出現的跨域問題。
1、如果你是自己寫的后端,可以添加配置類來避免跨域問題(建議使用)
package com.ftest.springboot.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 CrosConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") .allowCredentials(true) .allowedHeaders("*") .maxAge(3600); } }
這樣就不用擔心跨域了!
2、更改前端並不是太好,主要用於前端開發時的測試數據
進入terminal終端,安裝node模塊
npm i koa2-cors -D
js加上代碼:
const cors = require('koa2-cors');
app.use(cors());
就可以正常請求到了數據了!