Study notes-react's ajax package use and proxy settings


React realizes the important function of dynamically obtaining data. Sending ajax in react generally uses fetch. And because of cross-domain issues, a proxy needs to be set up.

1. Installation of fetch package: 

Enter the following code in the command window in the project folder:

yarn add isomorphic-fetch

2. Package ajax:

Create a new folder named utils under the src folder of the project, and create a new http.js file in utils. And use export default to export the encapsulated function, it will be very convenient to import and use it on the required page.

import fetch from 'isomorphic-fetch';

function http(url, options={}) {
        // 告知服务器通过body节点携带的数据,按json字符串格式来理解和使用
        options.headers = {
                "Content-Type": "application/json",
                "Authorization": sessionStorage.getItem("token")
        };
        // 将调用http方法配置body携带的数据进行json字符串化
        if(options.body) options.body = JSON.stringify(options.body);
        return fetch(url, options)
        // 第一个then拿到的是fetch返回的结果,并不一定是服务器返回的结果
                .then(response => {
                        if(response.status === 200) return response;
                        else throw new Error(response.statusText);
                })
                .then(response => response.json())
                .then(({ code, data, msg }) => {
                        switch(code) {
                                case 200: return data;
                                case 401:
                                case 404:
                                case 199:
                                case 500:
                                default:
                                        throw new Error(msg);
                        }
                })
                .catch(error => {
                        alert(error.message);
                        // 返回一个永远是pending的Promise对象
                        return new Promise(() => {});
                })
}

export default http;

3. Set up proxy:

You can set up a proxy in package.json to solve cross-domain problems.

"proxy": "http://localhost:3000/"

You can also modify the port number:

"scripts": {
		"start": "set PORT=8888&&react-scripts start",
		"build": "react-scripts build",
		"test": "react-scripts test",
		"eject": "react-scripts eject"
},

4. Send ajax:

import http from '../../utils/http.js';    // 导入http

// class中
async componentDidMount() {
    // 组件挂载完毕
    let listMain = await http("/category/list/0");
    let listSub = await http("/category/list/1");
    this.setState({  listMain, listSub, activeId: 1 });
}

The above is the ajax package and its use, and how to solve cross-domain problems. With ajax, we can get data dynamically.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109478792