Continuing with the previous article, if you want to review the previous article, please click here to see the EggJS Implementation Server request tutorial document-1

Iii. User details Interface Development (POST request)

egg

With the get request example, the POST implementation works the same way.

/app/router/detail.js

'use strict';

module.exports = app= > {
  const { router, controller } = app;
  router.post('/api/getUserDetail', controller.home.userDetailController);
};
Copy the code

/app/controller/home.js

.class HomeController extends Controller {
  async userListController(){... }async userDetailController() {
    const { ctx } = this;
    ctx.body = {
      data: 'userDetail query success'.success: true}; }}...Copy the code

Since a POST request cannot invoke the interface through a URL, our primary goal is to successfully invoke the interface:

web

# terminal execution, using the command line to create a page
alita g pages userDetail
Copy the code

/src/pages/userDetail/service.ts

import { request } from 'alita';

export async function queryUserDetail(params: any) :Promise<any> {
  return request('/api/getUserDetail', { method: 'post'.data: params });
}
Copy the code

/src/pages/userDetail/index.tsx

import React, { FC } from 'react';
import { useRequest } from 'alita';
import { queryUserDetail } from './service';
import styles from './index.less';

interface UserDetailPageProps {
  location: any;
}

const UserDetailPage: FC<UserDetailPageProps> = ({ location }) = > {
  const { id } = location.query;
  const { data } = useRequest(() = > queryUserDetail({ id }));
  return <div className={styles.center}>{data}</div>;
};

export default UserDetailPage;
Copy the code

Click any item on the list page to jump to the user details page. The url is http://localhost:8000/#/userDetail? id=1

But the request did not seem to be as successful as expected.

Interface 403. Error message {“message”:”invalid CSRF token”} is displayed.

Baidu learned that the framework has a built-in security system, which is enabled by default to prevent XSS attacks and CSRF attacks. See Egg Post failed {message: ‘invalid CSRF token’} solution for the following solution

egg

/ config/config. Default. Js:

config.security = {
  csrf: {
    headerName: 'x-csrf-token'.// Customize the request header}};Copy the code

web

Add x-csrF-token to headers;

/src/utils/index.ts

// Encapsulate the method to get cookies
export const getCookie = (name: any) = > {
  var arr,
    reg = new RegExp('(^| )' + name + '= (/ ^; (*). | $) ');
  if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
  else return ' ';
};
Copy the code

/src/app.ts

Add headers to the request interface uniformly through middleware

const middleware = async (ctx: Context, next: any) => {
  // Here you can write something to do before requesting ctx.reqctx.req.options = { ... ctx.req.options,headers: {
      'x-csrf-token': getCookie('csrfToken'), // If the client is open, the egg writes the Key directly to the Cookie of the client. The Key is 'scrfToken', so it can be obtained directly}};await next();
  // Here you can do something with the response data ctx.res
};
Copy the code

egg

Finally, we get the input parameter requested by the interface in controller and reencapsulate the data of the parameter.

/app/controller/home.js

async userDetailController() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    console.log(ctx.request.body);
    ctx.body = {
      data: {
        id,
        name: `name${id}`,},success: true}; }Copy the code

When a call is made to the interface, the terminal displays ctx.request.body data.

Feat – user – the detail branch

4. Egg middleware

Middleware is written, and all requests go through middleware. Operations can be handled in middleware.

See the website for an example of Middleware.

This will implement a requirement to add the requestHeader parameter to the requestHeader. The interface side verifies the correctness of the requestHeader in the middleware. If correct, the process continues. If not, the interface cannot be requested.

egg

Create a new/Middleware folder under /app. This is also the convention used to store middleware.

/app/middleware/request.js

Do not rush to implement the function, to first try to increase the success of middleware.

As can be seen from the following code, if the middleware is successfully implemented, the terminal will display the parameters of options(config.default.js) and the input parameters of the request whenever there is an interface request.

'use strict';
module.exports = options= > {
  return async function requestMiddleware(ctx, next) {
    console.log(options.requestHeader, ctx.request.body);
    await next();
  };
};
Copy the code

/config.config.default.js

module.exports = appInfo= >{...// Omit some code here

    config.middleware = ['request']; // Add 'request.js' file to middleware

    // Add configuration parameters to 'request.js'
    exports.request = {
        requestHeader: 'hang'};return{... config, ... userConfig, }; };Copy the code

Go to http://localhost:8000/#/userDetail? id=2

The middleware configuration is successful. Start writing functional code

/app/middleware/request.js

module.exports = options= > {
  return async function requestMiddleware(ctx, next) {
    const { requestHeader } = ctx.request.header;
    if (ctx.request.header.requestheader === options.requestHeader) {
      await next();
    } else {
      ctx.status = 403;
      ctx.body = {
        data: 'access was denied'.success: false}; }}; };Copy the code

web

If an interface request fails, it is displayed and processed in the Web middleware.

/config/config.ts

export const request = {
  prefix: ' '.// A unified request header
  middlewares: [middleware],
  errorHandler: (error: ResponseError) = > {
    if (error.response.status === 403) {
      Toast.fail('access was denied'); }}};Copy the code

/config/config.ts

const middleware = async (ctx: Context, next: any) => {
  // Here you can write something to do before requesting ctx.reqctx.req.options = { ... ctx.req.options,headers: {
      'x-csrf-token': getCookie('csrfToken'), // If the client is open, the egg writes the Key directly to the Cookie of the client. The Key is 'scrfToken', so it can be obtained directly
      requestHeader: 'hang',}};await next();
};
Copy the code

After header requestHeader is added to a Web interface request, the interface requests again.

Feat – branch of middleware

For the next article, please refer to the EggJS implementation server request tutorial document-3