方式一  本地访问

将react的build包直接放在SpringBoot项目的WebApp下,可以直接通过相对路径进行访问。

方式二 跨域访问-服务器端开放跨域

以Servlet为例,response配置为允许跨域。

response.setHeader("Access-Control-Allow-Origin", "*"); //参数*代表可访问的地址或域名,* 代表不限制客户端,可以"127.0.0.1"或"www.baidu.com"。

package com.example.demo.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HellowServlet2
 */
@WebServlet("/HellowServlet2")
public class HellowServlet2 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HellowServlet2() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("getParameter: " + request.getParameter("id"));
        System.out.println("getParameterMap: " + request.getParameterValues("books"));
        
        
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json");
        response.setContentType("application/x-www-form-urlencoded");
        
        response.getWriter().println("{\"name\":\"lance\",\"id\":\"44\"}"); //JSONUtil.parse(CommonResult.forbidden(e.getMessage()))
        response.getWriter().flush();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

客户端访问,使用axios

    axios.request({
            headers:{  //非必须
                "Content-Type":"application/x-www-form-urlencoded"
            },
            url:Url,
            params:Params//,    //参数类型二
            //withCredentials: true//跨域设置,不可用
        })
          .then(function (response) {
            let data =response.data
            console.log(data.name);

            ts.getData(data.name);
          })
        //   .then(aaa => this.setState({ //在axios中setState方法二
        //       argName:aaa.data.name
        //   }))
          .catch(function (error) {
            console.log(error);
          });
          
          
    getData(newName){
        this.setState({
            argName: newName
        });
    }

方式三 跨域访问-客户端开放跨域

利用axios自带的代理服务:proxy。

"proxy": "http://127.0.0.1:8084"

package.json配置:

{
  "name": "react-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "homepage": ".", 
  "main": "index.html",
  "proxy": "http://127.0.0.1:8084"
}

类组件调用

// let  BaseURL="http://127.0.0.1:8084"
        let  BaseURL="/api" //默认proxy代理的接口
        let  Url="/HellowServlet2"



        // let Books = ['aaa','bbb'];

        let Params= {
            "id" : "3",
            "name": "ll",
            "age": "18"
        }

        //axios.defaults.headers["Content-Type"] = "application/x-www-form-urlencoded";

        //全局配置baseURL[URL三个字母必须大写,不然axios不认]

        let ts = this;//在axios中setState方法一

        axios.request({
            headers:{  //非必须
                "Content-Type":"application/x-www-form-urlencoded"//,
                // "Access-Control-Allow-Origin":"http://127.0.0.1", //不可用
                // "Access-Control-Allow-Credentials": "true"//不可用
            },
            // method: 'get', //非必须
            //baseURL:BaseURL,//使用proxy时,无需配置
            url:Url,
            // data:Qs.stringify(Params), //参数类型一
            params:Params//,    //参数类型二
            //withCredentials: true//跨域设置 //不可用
        })
          .then(function (response) {
            let data =response.data
            console.log(data.name);

            ts.getData(data.name);
          })
        //   .then(aaa => this.setState({ //在axios中setState方法二
        //       argName:aaa.data.name
        //   }))
          .catch(function (error) {
            console.log(error);
          });
    }

    getData(newName){
        this.setState({
            argName: newName
        });
    }
 

标签智能推荐:

网络请求ajax fetch axios

ajax:axios:http://www.axios-js.com/

React 网络请求

React网络请求使用axios完成网络请求importReactfrom'react';importaxiosfrom'axios';importPubSubfrom'pubsub-js'importReconnectingWebSocketfrom"reconnecting-websocket";import'./App.css';importShowdetilComponentfrom'./

前后端数据交互(五)——什么是 axios

成axios(url,config)。具体的其他方法分别为:axios.request(config)axios.get(url,config)axios.delete(url,config)axios.head(url,config)axios.options(url,config)axios.post(url[,data[,config]])axios.put(url[,data[,confi

axios get,post请求时带headers

背景react前端写接口的时候,发现get请求加了headers之后发出来的请求不通,通过检查,发现写的语法有问题,在此记录下:post请求axiospost请求时带headers:axios.post("http://xxx.com/xxx/xxx/xxx?",{'queslistid':this.kemuid},{headers:{'token':Cookies.get('token'),'p

eslint-config-react-app npm

eslint-config-react-appnpm

2021/11/15

一、Vue了解知识点1.先有的Angular和React,再有Vue。并且Vue结合了二者的优点,借鉴了Angular的结构模板和数据绑定技术,借鉴React的组件化和虚拟DOM技术2.Vue的扩展插件2.1vue-cli:vue脚手架2.2vue-resource、axios:ajax请求2.3vue-router:路由2.4vuex::状态管理2.5mint-ui:基于vue的UI组件库(移动

react初体验

ReactDeveloperTools,这个跟vue的devtools是一样的功能,在Chrome浏览器上,对程序进行审查调试的工具 安装方法有:1、谷歌商店。2、github。3、第三方网站下载,https://www.cxyhub.com/4、react的全家桶react的全局桶跟vue的全家桶是官方不同,没有官方一套,所以react的全家桶挺多的,选择上见仁见智了比如:redux、

使用 WebpackDevServer 实现请求转发

:{'/react/api':'http://www.dell-lee.com'}}经过上面的配置之后,当在axios中请求/react/api时就相当于请求的是http://www.dell-lee.com这台服务器。index.js中请求数据importaxiosfrom'axios';axios.get('/react/api/header.json').then((res)=>{co

axios 的二次封装及使用

1//将axios再次封装2importaxiosfrom'axios';//npmi-Saxios34importQsfrom'qs'//npmi-Sqs56//提示组件mint-ui中的提示组件78axios.defaults.withCredentials=true;//false不跨域true跨域9axios.defaults.headers.common["token"]=localSt

create-react-app react 使用dll抽离公共库,大幅缩减项目体积,及项目打包速度

dule.exports={entry:{//需要提取的库文件vendor:['react','qs','react-helmet','echarts','echarts-for-react','antd','ahooks','aws-sdk','react-dom','react-redux','redux','react-router-dom','react-router-config','r