react与后端交互(包括通过axios进行跨域访问)
方式一 本地访问
将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 }); }