其他分享
首页 > 其他分享> > react跨域访问,通过axios

react跨域访问,通过axios

作者:互联网

配置package.json

 "proxy": { //关键代理
    "/api": {
      "target": "http://127.0.0.1:8084",
      "changeOrigin": true
    }
  }

 

{
  "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": { //关键代理
    "/api": {
      "target": "http://127.0.0.1:8084",
      "changeOrigin": true
    }
  } 
}

类组件调用

let  BaseURL="/api"
        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,
            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
        });
    }

 

标签:axios,跨域,react,let,scripts,data,name
来源: https://www.cnblogs.com/loge/p/16272249.html