提问人:Wolf Ganger 提问时间:11/17/2023 最后编辑:Wolf Ganger 更新时间:11/18/2023 访问量:32
即使在 Spring Boot Server 中使用 CORS 配置,CORS 也存在跨域问题 [已关闭]
CORS cross-origin problem even with CORS configuration in Spring Boot Server [closed]
问:
我的Spring Boot服务器中已经有CORS配置类:
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization")
.maxAge(3600); // Max age of the preflight request in seconds
}
}
问题是,即使使用该类,AXIOS 仍然会失败,并显示以下错误:
我还缺少什么?在我的后端有其他 POST 请求时,我没有任何问题
我还尝试在控制器本身中使用@CrossOrigin(origins=“*”),但结果是一样的
@RestController
@RequestMapping("/classification/")
@CrossOrigin(origins = "*")
public class ClassificationController {
这是进行查询的类:
export default function NewClassification() {
const [classification, setClassification] = useState([]);
async function addClassification(URL, classification) {
const createdClassification = await postRequest(URL,classification);
setClassification(createdClassification)
}
console.log(useSearchParams().get('name'))
const videogameName= useSearchParams().get('name')
return (
<Layout>
<div>
<form>
<input type='text' id='entity' placeholder='Write entity name'/>
<input type='text' id='age' placeholder='Write age of the label'/>
<input type='text' id="url" placeholder='Write URL of the homepage of the entity'/>
<input type='text' id='country' placeholder='Write country where the entity belongs'/>
<input type='button' value="Add new classification" onClick={e => addClassification("/classification/"+videogameName,{system:document.getElementById("entity").value,
country:document.getElementById("country").value,tag:document.getElementById("age").value,url:document.getElementById("url").value})}/>
</form>
</div>
</Layout>
)
}
这是处理请求并将其发送到后端的类:
import axios from "axios";
const axiosClient = axios.create();
axiosClient.defaults.baseURL = "http://<ip>:8080"
axios.defaults.headers.post['Content-Type'] = 'application/json';
export async function postRequest(URL, payload){
const response = await axiosClient.post(URL, payload, {
headers: {crossDomain: true},
validateStatus: function (status) {
return true;
}})
//.then(response => response)
//.catch(err => console.log(err))
console.log(response)
return response.data
}
答: 暂无答案
评论
crossdomain
AXIOS still fails
- 并不少见 - 检查浏览器开发人员工具 - 您的请求是否发送标头?如果是这样,请找出原因 - 问题出在客户端,但您只显示了服务器代码crossdomain
headers: {crossDomain: true}