Ajax request and axios package in front-end development

Table of contents

browser http request

Synchronize js tags across domains and urls

Asynchronous ajax, websock protocol

Ajax is an asynchronous technical term, and the earliest API is xhr (XMLHttpRequest)

fetch es6 api

axios

Package axios

src/utils/request.ts

src/utils/func.ts

SSO (Single Sign-On) single sign-on, one login can access multiple independent programs

regular expression

common characters

Forward/Backward Lookup: Matches what is in parentheses (excluding parentheses)

src/api/common.ts

src/views/components

Basic Knowledge Review

url parameter

location attribute value

Same Origin Policy

token sum cookie

Replace cookies (simulate users with different permissions in development)

A. Manually

B. Set index.html 

C. Browser extension applet: get/set multiple with one click

web security

XSS cross-site scripting attack Cross-Site Scripting (execute script reading when logging in)

CSRF cross-site request forgery Cross-site request forgery (credential request)

SQL injection attack (submit form/enter domain name to execute SQL command)

DDoS attack distributed denial of service Distributed Denial of Service (request overload)


browser http request

Synchronize js tags across domains and urls

<img src>,<link href>

Asynchronous ajax, websock protocol

Ajax is an asynchronous technical term, and the earliest API is xhr (XMLHttpRequest)

fetch es6 api

Promise-based, easy to use 

axios

  • Isomorphic, that is, the same code is available on the nodejs side and the browser side
  • Use xhr in the browser, and use Node's built-in http module in Node.js.
// 在浏览器中,根据其Content-Type头信息,自动转换数据
axios.get('/api/data').then(response => {
  // response.data 将是一个JavaScript对象
});

// 在Node.js中手动设置响应数据类型
axios.get('/api/data', { responseType: 'json' }).then(response => {
  // response.data 将是一个JavaScript对象
});
  • The new version of axios also supports fetch
  • Third-party libraries are based on native API, so axios is still based on xhr

[JavaScript] 20,000 characters! Understand the difference between Ajax, Fetch and Axios at one time~ Develop Paper

Package axios

src/utils/request.ts request/response interceptor

import service from 'axios'
import { handleSSO } from '@/utils/func'
import router from '@/router/index'

// 请求拦截器
service.interceptors.request.use(
  (config: any) => {
    // 在请求头中添加XMLHttpRequest字段
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    return config
  },
  (error: any) => {
    console.log('request:', error) // 用于调试的错误信息
    return Promise.reject(error)
  }
)

function errorMsgTips(msg: any) {
  window.$message.error(msg)
}

// 响应拦截器
service.interceptors.response.use(
  (response: { data: any; config: any }) => {
    const resData = response.data || {}
    if (resData.code === 302) {
      // 如果响应码为302,进行页面重定向到指定链接
      window.location.href = `https://www.example.com/path/to/resource.html/domain=${location.host}&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`
    } else if (resData.code == 0 || resData.code == 200) {
      // 如果响应码为0或200,则直接返回响应数据
      return resData
    } else if (resData.code == 4004) {//自定义响应码
      // 如果响应码为4004,说明没有权限,跳转至无权限页面
      router.push({
        path: '/notPermission'
      })
    } else {
      // 其他情况下,显示错误提示消息
      errorMsgTips(resData.message || '接口错误,请稍后重试')
    }
  },
  (error: any) => {
    if (service.isCancel(error)) {
      console.log('取消请求 error -> ', error)
      return
    }
    if (error && error.response && error.response.status === 302) {
      if (process.env.NODE_ENV === 'development') {
        // 如果是开发环境,并且错误码为302,显示替换SSO_SESSION_ID的提示
        errorMsgTips('请替换Cookies里的SSO_SESSION_ID')
        return
      } else {
        // 非开发环境下,进行单点登录重定向
        window.location.href = handleSSO('login')
      }
    } else if (error && error.stack.includes('timeout')) {
      // 如果错误信息中包含"timeout",显示接口超时错误提示
      errorMsgTips('接口超时')
      return
    } else if (error && error.stack.includes('Network')) {
      // 如果错误信息中包含"Network",显示网络异常错误提示
      errorMsgTips('网络异常')
      return
    }
    return Promise.reject(error)
  }
)

export default service

src/utils/func.ts tools

/**
 * 清除会话
 * @param
 */
function clearSession() {
  //匹配不包含空格和分号的字符,该字符后面必须跟着一个等号。这会返回一个由cookie键组成的数组。
  const keys = document.cookie.match(/[^ =;]+(?=\=)/g)
  if (keys) {
    for (let i = keys.length; i--; )
     //) 创建了一个代表时间戳 0 的 JavaScript Date 对象,并将其转换为 UTC 字符串。
     //这个时间对应于 1970 年 1 月 1 日 协调世界时 (UTC) 时间 00:00:00。
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
  }
  sessionStorage.clear()
  localStorage.clear()
}

/**
 * SSO登入登出
 * @param SSOtype
 * login登入
 * logout登出
 */
export function handleSSO(SSOtype: string): string {
  const hostStr = 'passport.example.com'
  clearSession()
  return `https://${hostStr}/${SSOtype}?service=` + encodeURIComponent(window.location.origin)
}

SSO (Single Sign-On) single sign-on, one login can access multiple independent programs

Usually implemented by token/cookie

regular expression

common characters

· Matches any single character except a newline character
* Matches the preceding character zero or more times. For example, "zo*" matches "z" or "zoo".
+ matches the previous character one or more times. For example, "zo+" matches "zoo", but not "z".
? matches the preceding character zero or one time. For example, "a?ve?" matches "ve" in "never".
x|y matches x or y
{n} matches n times. n is a non-negative integer
{n,} n is a non-negative integer. At least Matches n times. For example, "o{2,)" does not match the "o" in "Bob", but matches all o's in "foooood". "o{1}" is equivalent to "o+"." o{0,}" and "o*" are equivalent.
{n,m}m and n are non-negative integers. Match at least n and at most m times. For example, "o{1,3]" and "fooooood" Matches the first three o's in "o{0,1}" and "o?" are equivalent.
[xyz] matches any character within the brackets. For example, "[abc]" and "a in "plain" "match.

[^xyz] matches any character that is not inside the brackets. For example, "[^abc]" matches the "p" in "plain".
[az] range of characters. Matches any character in the specified range. For example, "[az]" matches any lowercase alphabetic character in the range "a" through "z".

[^mz] negates a range of characters. Matches any character not in the specified range. For example, "[mz]" matches any character not in the range "m" through "z".

Forward/Backward Lookup: Matches what is in parentheses (excluding parentheses)

Backward lookup: (?<=exp) is a string that starts with exp , but does not contain itself .

Forward lookup: (?=exp) matches the string ending with exp , but does not contain itself .

Negative lookbehind : (?<!exp)  , the subexpression specified before cannot be matched .

Negative lookahead :: (the subexpression specified after cannot be matched .

The positive lookahead assertion  means  that the assertion is made at the position before  (?=\=) the matching equal sign  , that is, the forward position must be followed by the equal sign  to match. Such assertions do not consume actual characters.==

Lookahead  (?==) means match the equal sign  =and  = include the equal sign in the match result. This lookup consumes the character equal  = sign.

src/api/common.ts package request

import request from '@/utils/request'
const baseUrl = process.env.NODE_ENV === 'development' ? '/test' : ''
const mock = false

// 查看自己信息接口
export const commonQuery = (data: any) => {
  const url = mock ? `${baseUrl}/common/query` : `${baseUrl}/mock/query`
  return request.post(url, data)
}

// 查看自己信息接口
export const getUserInfo = () => {
  const url = `${baseUrl}/menu/userInfo`
  return request.get(url)
}

src/views/components requests

import * as API from "@/api/common"
...
 API.commonQuery(params).then((res: any) => {
      console.log('res::::', res)
    })

Basic Knowledge Review

url parameter

http://example.com/page?param1=value1&param2=value2#section1

Separate the actual URL and parameters
& Separator between parameters specified in the URL
= The left side is the parameter name, the right side is the parameter value
#

Anchor (Anchor), used to identify a specific location or element in the document,

Used only on the client side and processed by the browser, not sent to the server

Instructs the browser to scroll to id="section1"the element with the .

location attribute value

The global object of window, representing the current page http://www.example.com/path/index.html

window.location.href: get/set url

window.location.orgin: protocol, hostname and port number sections

//https://www.example.com:8080/page.html
//     ://               :
//https%3A%2F%2Fwww.example.com%3A8080。
encodeURIComponent(window.location.origin)
//encodeURIComponent用于将字符串中的特殊字符(空格、&、+、= 、?)转换为编码形式,确保URL中不包含任何无效字符



//查询参数时 或者 动态参数时 需要encodeURIComponent
const url = 'https://example.com/api?param=' + encodeURIComponent(queryParam);
window.location.href =`https://www.example.com/path/to/resource.html/domain=${location.host}&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`

window.location.protocol: protocol http

window.location.host: host + port (host:8080)/IP address (127.123.32.1 unique)/domain name (www.example.com mnemonic)

window.location.hostname: host host

window.location.port: port 8080

window.location.pathname: resource path path/index.html, resource index.html

window.location.hash:

window.location.search: search

var searchParams = new URLSearchParams(window.location.search);
console.log(searchParams.get('name')); // 输出 "John"

Same Origin Policy

Same origin/domain: As the name suggests, the domain name must be the same including the prefix, and of course the port number

But the cookie can be different starting from the port number

Cross-origin requests do not carry cookies by default.

However, cross-origin requests with cookies can be allowed by setting the CORS (Cross-Origin Resource Sharing) header.

withCredentialsThe attribute is trueto tell the browser to carry the cookie in the request.

token sum cookie

certificate token cookie
cross domain

The token is completely managed by the application, so it can avoid the same-origin policy

Server-side generation management, not cross-domain
with session

The mobile terminal does not support cookies very well, so token is commonly used on the mobile terminal

session needs to be implemented based on cookie

Replace cookies (simulate users with different permissions in development)

A. Manually

B. Set index.html 

<!DOCTYPE html>
<html lang="">
  <head>
...
    <div id="app"></div>
    <script>
      document.cookie = 'sso_ticket=xx'
    </script>
  </body>
</html>

C. Browser extension applet: get/set multiple with one click

Get the cookies in the project web page, and then set it in the local project web page


web security


XSS cross-site scripting attack Cross-Site Scripting (execute script reading when logging in)

solve:

  • The url parameter is escaped using the encodeURIComponent method
  • Try not to insert HTML content with InnerHtml

CSRF cross-site request forgery Cross-site request forgery (credential request)

Solution: add verification code , use token

SQL injection attack (submit form/enter domain name to execute SQL command)

Solution: Convert some special characters through regular expressions when entering the form

DDoS attack distributed denial of service Distributed Denial of Service (request overload)

solve:

  • Limit the frequency of single IP requests.
  • Check for privileged port openings

Guess you like

Origin blog.csdn.net/qq_28838891/article/details/131445311