react+springboot解决跨域问题的3种方法

2019-04-02  本文已影响0人  代码届的泥石流sc

在学习的过程,遇到react 项目axios访问后台springboot项目,发现404 跨域问题。
其中涉及到的方法有:
1、webpack.config.js文件用设置代理proxy;
2、直接在springboot项目的Controller文件加入注解@CrossOrigin,前端请求中直接写入后台的uri
3、把react项目部署到 nginx 服务器上.
以前自己查找方法的时候,总是抱怨别人的写的不详细,但是真正 自己写技术文章的时候,才发现有时候真的想简单点,而且有时也考虑的比较少,多多包涵。
axios:对应的文档可以到github 搜索axios .地址:https://github.com/search?q=axios,第一个就是,进去里面就是axios的安装以及用法

axios.png

好了 下面将分别说一下对应的方法:
1、设置代理proxy,在webpack.config.js文件修改devServer

var host = '192.168.**.***';
...
devServer: {
        hot: true,
    host: host,
        compress: true,
        port: 3457,
        historyApiFallback: true,
        contentBase: path.resolve(__dirname),
        publicPath: '/build/',
        proxy: {
            "/api/*": {
                //host 即为你后台springboot的地址 8083对应的端口号
                target: `http://{host}:8083/`,  
                secure: false,
                changeOrigin: true,
                // 前端请求uri:api/user  解析出来的结果就是http://{host}:8083/user  即去掉api前缀
                pathRewrite: { '^/api': '' }
            }
        },
        stats: {
            modules: false,
            chunks: false
        },
    },

前端的访问:

axios.post('/api/t-test/getTtestById', 
        querystring.stringify({
            id: '42',
            lastName: '你好'
          })
          )
          .then(function (response) {
            console.log("打印跨域返回数据:"+JSON.stringify(response.data));
          })
          .catch(function (error) {
            console.log(error);
          });

2、通过注解的方式@CrossOrigin
在对应的Controller文件上增加@CrossOrigin ,也可以单独对需要跨域的方法增加注解

...
@CrossOrigin
@Controller
@RequestMapping("/t-test")
public class TTestController {
...

前端访问的方式

TestKuayu = () =>{
        console.log("测试跨域问题!");
        //直接把springboot项目的uri写入请求中,如果不想每次都写,可以把uri封装到一个变量中
        axios.post('http://localhost:8989/t-test/getTtestById', 
        querystring.stringify({
            id: '42',
            lastName: '你好'
          })
          )
          .then(function (response) {
            console.log("打印跨域数据:"+JSON.stringify(response.data));
          })
          .catch(function (error) {
            console.log(error);
          });

    }

3.部署到nginx 服务器,详细讲这个吧

(1)首先安装nginx 官网:http://nginx.org/

微信截图_20190402163648.png
nginx版本.png
(2) 配置nginx
解压 先别启动nginx.exe,打开dos窗口 win+R 输入cmd. 进入到nginx目录 下面是我的目录 ,
nginx会话.png
也可以ctrl+alt+. 打开任务管理->详细信息 能看到nginx启动成功
任务管理器.png
(3)react项目运行npm run build
build.png
之后在文件目录找到build文件夹 ,下面是我的打包好文件目录
builds.png

把这里的文件都复制到nginx的安装目录下的html文件夹里面


nginx_html.png

注意:修改nginx 目录 conf文件夹下nginx.conf 可以用sublime text打开 也可以用文本文件等等。。

修改 http 下sever:

...
server {
        listen       8800;  #代理的端口
        server_name  localhost;  #代理的地址

        #root:D:\react\reactdemo\reactdemo01\build;
        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;          # 默认的入口文件
            index  index.html index.htm;
        }

        location /api/ {          # /api 代理到下面 地址  就是修改成你后台的uri
            proxy_pass http://192.168.*.*:8989/;
        }
....

修改了配置 文件 记得要重启一起nginx : nginx -s reload

react 测试 贴出部分代码

<button onClick={this.TestKuayu}>测试跨域问题</button>

TestKuayu = () =>{
        
        console.log("测试跨域问题!");
        axios.post('/api/t-test/getTtestById', 
        querystring.stringify({
            id: '42',
            lastName: '你好'
          })
          )
          .then(function (response) {
            console.log("打印nginx跨域:"+JSON.stringify(response.data));
          })
          .catch(function (error) {
            console.log(error);
          });

    }

nginx部署目录.png 后台.png r.png
rs.png

至此全部完成,有什么不正确的,可以指出一起交流。
ly_dv 一个小菜鸟

上一篇 下一篇

猜你喜欢

热点阅读