zoukankan      html  css  js  c++  java
  • 前端页面调用spring mvc接口发生跨域问题解决方案

    使用spring mvc开发了一个Restful接口供前端调用

    @GetMapping("/hello")
    ResponseEntity<?> hello() {
        Map<String, Object> resMap = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append("{").append('"').append("key").append('"').append(":").append('"').append(123).append('"').append("}");
        sb.append("]");
        resMap.put("returnInfo", sb.toString());
        return new ResponseEntity<Map<String, Object>>(resMap, HttpStatus.OK);
    }
    前端调用如下:
    <Button type="primary" onClick={function () {
        fetch("http://localhost:8080/hello").then(data=>{
            // text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取和后台返回的数据
            return data.text();
        }).then(ret=>{
            // 注意这里得到的才是最终的数据
            console.log(ret);
        })
    }}>Primary Button</Button>
    但是页面报错,F12后错误提示如下:

     判断应该是跨域问题,百度后发现spring mvc已经有很好的解决方案,添加@CrossOrigin即可。

    @CrossOrigin
    @GetMapping("/hello")
    ResponseEntity<?> hello() {
        Map<String, Object> resMap = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append("{").append('"').append("key").append('"').append(":").append('"').append(123).append('"').append("}");
        sb.append("]");
        resMap.put("returnInfo", sb.toString());
        return new ResponseEntity<Map<String, Object>>(resMap, HttpStatus.OK);
    }
    接口调用成功

     参考链接:https://segmentfault.com/a/1190000011174645

    越努力越幸运!
  • 相关阅读:
    Pycharm中运行Python代码的几种方式
    Git同步Python代码
    抓包工具Charles的使用
    jmeter进行的接口测试和压力测试
    并发的HTTP请求,apache是如何响应的,以及如何调用php文件的
    http 请求头部解析
    display_errors","On");和error_reporting 区别和联系
    http
    curl
    正则 惰性和非惰性匹配
  • 原文地址:https://www.cnblogs.com/tudouer/p/14095607.html
Copyright © 2011-2022 走看看