In the previousReact Experience out of the box

Any system, to provide the premise of interactive capabilities, needs to carry out data transfer through the network to the ground.

The most primitive web request that a browser can make via the XMLHttpRequest object. There are many web request modules that encapsulate XMLHttpRequest, most commonly Axios

A common request framework for the front endAxios

Axios is used for front-end browsers and Node.js server requests. The browser side initiates a request encapsulating XMLHttpRequest. The Node side initiates a request using the node.js native HTTP/HTTPS module.

Network request mode

  • A GET request will send a request to the database for data, so as to obtain information. The request is just like the select operation of the database. It is only used to query the data, and does not modify or add data. No matter how many times you do it, the result is the same
  • A POST request is similar to a PUT request in that it sends data to the server, but it changes the type of data and other resources, just as database inserts create new content. Almost all current commit operations are POST requests
  • A PUT request changes information by sending data to the server (unlike GET). It is like an update to a database, modifying the content of the data but not increasing the type of data, etc. This means that no matter how many times a PUT operation is performed, the result is the same
  • A DELETE request, as its name implies, is used to DELETE a resource, like a database DELETE operation
  • .

The above request mode is RESTful and operates server resources according to different request modes

The common request modes are GET and POST. Because antD-Design-Pro is used, the framework integrates and encapsulates UMI-Request. All network requests used in SO projects can be operated by UMI-Request

If you want to make a request using Axios, refer to the Axios Instructions in Chinese

umi-requestA simple layer is encapsulated in the project utils/request.js file.

Login interface structure

Adjust the moose – react – learn

Adjust route access. The original http://localhost:8000/user/login = > http://localhost:8000/login

  • Create the Login directory and move the original User/ Login directory file to Login/index.jsx

  • Modify the directory config/router.js

Too many changes. Access git commit records

Gitee.com/shizidada/m…

  • Rerun the program at http://localhost:8000/login

  • Default account admin or user Password ant.design

  • These accounts are used through the mock interface. The admin/ User accounts have different permissions, and different menus are displayed in the menu route

dockingreallyServer interface

  • For details, see the moose Operator Service server project
  • Run to view the Moose Operator Service README and environment preparations
  • The item is availableThe logininterface
  • reference
    • Spring Boot 2.x Quick Start
    • SpringBoot OAuth2.0 Authentication and authorization (password mode)
    • SpringBoot OAuth2.0 encapsulates the login and refresh token interface

POST localhost:7000/api/v1/account/login

  • AccountName // string Login account
  • Password // string Password
  • LoginType // string loginType (password and SMS verification code are supported)
  • Obtain the login user information

POST localhost:7000/api/v1/user/info

  • AccessToken // Validate token (returned after successful login)
  • Start the project and use PostMan for interface debugging

  • Access the user/info interface using accessToken

Front-end call interface

  • Change the proxy config/proxy.js to the moose Operator Service address http://localhost:7000
dev: {
    '/api/': {
      target: 'http://localhost:7000'.changeOrigin: true.pathRewrite: {
        A '^': ' ',}}},Copy the code
  • Modify the services/login. Js
export async function postAccountLogin(params) {
  // The real interface provided by the Moose service
  return request("/api/v1/account/login", {
    method: "POST".data: params,
  });
}
Copy the code
  • Modify the services/user. Js
export async function queryCurrent() {
  return request("/api/v1/user/info", { method: "POST" });
}
Copy the code
  • Rewrite the startup project and jump to http://localhost:8000/

    In this case, it is normal logic, because the user information interface will be accessed when you visit the home page. The user information interface needs permission to access, so the login interface will be redirected.

  • After modification code, warehouse view

Gitee.com/shizidada/m…

  • Modified corresponds to the interface field

Wrong commit

  • View the login screen, calledlogin model loginFunction, directly modifylogin model loginJust pass the parameters
.const handleSubmit = (values) = > {
    const { dispatch } = props;
    dispatch({
      type: 'login/login'.payload: {... values, type }, }); }; .// login modle => *login
  *login({ payload }, { call, put }) {
    // Deconstruct the parameters
    const { password, type, userName } = payload;
    // Reassemble the parameters
    const params = {
      loginType: type === 'account' ? 'password' : 'sms_code'.accountName: userName,
      password,
    };

    // Submit the processed parameters
    const response = yield call(postAccountLogin, params);
    yield put({
      type: 'changeLoginStatus'.payload: response,
    }); // Login successfully

    // Return code 200 to indicate success
    if (response.code === 200) {
      const urlParams = new URL(window.location.href);
      const params = getPageQuery();
      message.success('🎉 🎉 🎉 Login successful! ');
      let { redirect } = params;

      if (redirect) {
        const redirectUrlParams = new URL(redirect);

        if (redirectUrlParams.origin === urlParams.origin) {
          redirect = redirect.substr(urlParams.origin.length);

          if (redirect.match(# ^ \ /. * /)) {
            redirect = redirect.substr(redirect.indexOf(The '#') + 1); }}else {
          window.location.href = '/';
          return;
        }
      }

      history.replace(redirect || '/'); }},Copy the code
  • After modification

It’s still wrong after modification

Because the content-typ of umi-request is application/ JSON by default

The parameter interface provided by Moose service is not accepted by JSON. Moose service is (Application/X-www-form-urlencoded) by default, so errors will be reported

  • The solution

    First: modify moose service to accept parameters in JSON format

    Second: Modify umi-request request content-typ

  • The second solution is to modify the login interface

    export async function postAccountLogin(params) {
      return request("/api/v1/account/login", {
        method: "POST".// Add application/x-www-form-urlencoded
        requestType: "form".data: params,
      });
    }
    Copy the code
  • Enter account jiangjing password 123 to log in successfully

If the login succeeds, the login page will be redirected to the home page

  • This is because the Moose Operator Service uses OAuth 2.0 authorization to access the User /info interface and pass the accessToken parameter.

TODO:

Once logged in, save accessToken and continue to access other interfaces with accessToken

When accessToken expires, the token is refreshed and the interface is accessed normally

The DEMO source code:

Front end: gitee.com/shizidada/m…

The backend: gitee.com/shizidada/m…