【山竹记账-全栈】6.前后端联调:登录页面-倒计时-登录防护

以 vue 前端项目为例,紧接 “【山竹记账后端】16.部署应用和文档” 和 “【山竹记账前端-vue】16.制作 echarts 图表”


大纲链接 §

[toc]


1. 前端:拿到 API 文档 ⇧

前提条件

  • 后端已部署接口文档 http://server1:8080/index.html (server1 为已映射的 host 云服务器地址)
    • 域名可变,不会写死在 api 文档中
  • 前端已完成静态页面 https://github.com/xmasuhai/mangosteen-fe-0-publish
  • 目前需要实现 前端请求 POST /api/v1/validation_codes 发送邮箱地址

2. 前端+后端:第一次前后端联调接口 ⇧

添加点击事件,发送验证码 ⇧

src/views/SignInView.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { defineComponent, reactive } from 'vue'
import { MainLayout } from '@/components/layout/MainLayout.tsx'
import { SvgIcon } from '@/components/icons/SvgIcon.tsx'
import { FormContainer } from '@/components/form/FormContainer.tsx'
import { FormItem } from '@/components/form/FormItem.tsx'
import { cn } from 'cn'
import { formValidate } from '@/shared/validator/formValidate.ts'

export const SignInView = defineComponent({
  name: 'SignInView',
  setup(/* _props, _ctx */) {
    const formData = reactive({ email: '', validationCode: '' })
    const genOriginErrors = () => ({ email: [], validationCode: [] })
    const errors = reactive(genOriginErrors())
    const onSubmit = (e: SubmitEvent) => {
      e.preventDefault()
      Object.assign(errors, genOriginErrors())
      const newErrors = formValidate(formData, [
        { key: 'email', type: 'required', required: true, message: '必填' },
        // /.+@.+/
        {
          key: 'email',
          type: 'pattern',
          regexp: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
          message: '邮箱格式错误',
        },
        { key: 'validationCode', type: 'required', required: true, message: '必填' },
      ])
      Object.assign(errors, newErrors)
    }

    const sendValidationCode = () => {
      console.log('1111')
      // axios.post('/api/sendValidationCode')
    }
    return () => (
      <MainLayout>
        {{
          title: () => '登录',
          icon: () => <SvgIcon name="back-arrow" size="1.5em" />,
          default: () => (
            <div>
              <div class="flex flex-col justify-center items-center pt-42px">
                <SvgIcon name="mangosteen" class="w-64px h-68px" />
                <h1 class="text-[var(--app-name-text)] text-2em font-bold">山竹记账</h1>
              </div>
              <FormContainer onSubmit={onSubmit}>
                <FormItem
                  label="邮箱地址"
                  type="text"
                  v-model={formData.email}
                  hasErrorPlaceholder
                  placeholder="请输入邮箱,然后点击发送验证码"
                  error={errors.email?.join(',')}
                />
                <FormItem
                  label="验证码"
                  type="validationCode"
                  v-model={formData.validationCode}
                  onClick={sendValidationCode}
                  hasErrorPlaceholder
                  placeholder="请输入六位数字"
                  error={errors.validationCode?.join(',')}
                />
                <FormItem
                  type="submit"
                  buttonConfig={{ text: '登录' }}
                  class={cn('mt-2em')} />
              </FormContainer>
            </div>
          ),
        }}
      </MainLayout>
    )
  },
})
  • 添加 onClick={sendValidationCode}

src/components/form/FormItem.tsx

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// import ...

export type FormItemType =
  | 'text'
  | 'emojiSelector'
  | 'date'
  | 'submit'
  | 'button'
  | 'validationCode'
  | 'select'

interface FormItemProps {
  type?: FormItemType
  modelValue?: FormDataType[string]
  visibleValue?: boolean
  error?: string
  hasErrorPlaceholder?: boolean
  label?: string
  hasLabelColon?: boolean
  onClick?: () => void
  onChange?: () => void
  placeholder?: string
  // 以下类型待使用泛型 体操动态控制
  buttonConfig?: { level?: ButtonLevelType; text?: string }
  options?: Readonly<{ label: string; value: string }[]>
}
interface ButtonConfig {
  level?: ButtonLevelType
  text?: string
}

export const FormItem = defineComponent<FormItemProps>({
  name: 'FormItem',
  props: {
    type: { type: String as PropType<FormItemType> },
    label: { type: String as PropType<string>, default: '' },
    hasLabelColon: { type: Boolean as PropType<boolean>, default: true },
    modelValue: {
      type: [String, Number, null, undefined] as PropType<FormDataType[string]>,
      default: '',
    },
    visibleValue: { type: Boolean as PropType<boolean>, default: false },
    error: { type: String as PropType<string> },
    hasErrorPlaceholder: { type: Boolean as PropType<boolean>, default: false },
    placeholder: { type: String as PropType<string>, default: '' },
    // TODO: 以下类型待使用泛型组件-动态控制
    buttonConfig: {
      type: Object as PropType<ButtonConfig>,
      default: () => ({ level: 'default', text: '确认' }),
    },
    options: {
      type: Array as PropType<{ label: string; value: string }[]>,
      default: () => [],
    },
    onClick: { type: Function as PropType<() => void> , default: () => void 0 },
  },
  emit: ['update:modelValue', 'update:visibleValue'],
  setup(_props, _ctx) {
    const extraHint = ref('')
    const modelValue = useModel(_props, 'modelValue')
    const visibleValue = useModel(_props, 'visibleValue')

    const getIfNeedLabelFor = computed(() =>
      ['text', 'submit', 'button', 'date', 'select'].includes(_props?.type ?? ''),
    )
    const forId = useId()
    const getLabelFor = computed(() =>
      getIfNeedLabelFor.value ? `form-item-${_props.type}-${forId}` : '',
    )
    const itemTypeSwitchContent = computed(() => {
      switch (_props.type) {
        case 'text':
          return (
            <InputText
              error={_props.error}
              v-model={modelValue.value}
              placeholder={_props.placeholder}
              forId={getLabelFor.value}
            />
          )
        case 'select':
          return (
            <SelectOrigin
              forId={getLabelFor.value}
              v-model={modelValue.value}
              options={_props.options}
              error={_props.error}
              placeholder={_props.placeholder}
            />
          )
        case 'emojiSelector':
          return (
            <EmojiSelector
              v-model={modelValue.value}
              v-model:extraHint={extraHint.value}
              hasError={!!_props.error}
            />
          )
        case 'submit':
        case 'button':
          return (
            <BarButton
              level={_props.buttonConfig?.level}
              forId={getLabelFor.value}
              type={_props.type}
              text={_props.buttonConfig?.text}
              onClick={_props.onClick}
            />
          )
        case 'date':
          return (
            <InputDatePickerPopup
              title={_props.label}
              placeholder={_props.placeholder}
              forId={getLabelFor.value}
              v-model={modelValue.value}
              v-model:visibleValue={visibleValue.value}
              error={_props.error}
            />
          )
        case 'validationCode':
          return (
            <>
              <InputText
                error={_props.error}
                v-model={modelValue.value}
                forId={getLabelFor.value}
                placeholder={_props.placeholder}
                class={cn('w-[9.5em]')}
              />
              <BarButton
                onClick={_props.onClick}
                text="发送验证码"
                class={cn('ml-1em')} />
            </>
          )
        case undefined:
          return _ctx.slots.default?.()
      }
    })

    return () => (
      <div class="form-item-sc">
        {/* 标签 */}
        {_props.label && (
          <LabelOrDivWrapper
            ifUseLabelTag={getIfNeedLabelFor.value}
            labelFor={getLabelFor.value}
            label={_props.label}
            hasLabelColon={_props.hasLabelColon}
            extraHint={extraHint.value}
          />
        )}

        {/* 内容 */}
        <div class={cn('form-item-content-sc', 'grow-1 children:grow-1')}>
          {itemTypeSwitchContent.value}
        </div>

        {/* 错误 */}
        {(_props.error || _props.hasErrorPlaceholder) && (
          <div class={cn('form-item-error-sc')}>
            <span>{_props.error ?? ' '}</span>
          </div>
        )}
      </div>
    )
  },
})
  • 给 <BarButton> 添加 onClick 属性

src/components/BarButton.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { defineComponent, type PropType } from 'vue'
import { cn } from 'cn'

export type ButtonFeatType = 'button' | 'submit' | 'reset'
export type ButtonLevelType = 'primary' | 'success' | 'warning' | 'danger' | 'default'

interface BarButtonProps {
  type?: ButtonFeatType
  level?: ButtonLevelType
  forId?: string
  text?: string
  onClick?: (e: MouseEvent) => void
}

export const BarButton = defineComponent<BarButtonProps>({
  name: 'BarButton',
  props: {
    type: { type: String as PropType<ButtonFeatType>, default: 'button' },
    level: { type: String as PropType<ButtonLevelType>, default: 'primary' },
    text: { type: String as PropType<string>, default: undefined },
    forId: { type: String as PropType<string>, default: undefined },
    onClick: { type: Function as PropType<(e: MouseEvent) => void>, },
  },
  setup(_props, _ctx) {
    const levelHashClassHash: Record<ButtonLevelType, string> = {
      primary: cn('bg-[var(--button-bg-primary)] b-[var(--button-bg-primary)]'),
      success: cn('bg-[var(--button-bg-success)] b-[var(--button-bg-success)]'),
      warning: cn('bg-[var(--button-bg-warning)] b-[var(--button-bg-warning)]'),
      danger: cn('bg-[var(--button-bg-danger)] b-[var(--button-bg-danger)]'),
      default: cn('bg-[var(--button-bg-default)] b-[var(--button-bg-default)]'),
    }
    return () => (
      <button
        {...(_props.forId ? { id: _props.forId } : {})}
        type={_props.type}
        onClick={_props.onClick}
        class={cn(
          `bar-button ${levelHashClassHash[_props.level ?? 'primary']}`,
          'b-1 b-solid rounded-[var(--button-radius)]',
          'text-[var(--button-text-color)] font-size-[var(--button-text-size)]',
          'where:(w-[100%] h-[var(--button-height)] p-x-1em p-y-[0.5em])',
        )}>
        {_props.text ?? _ctx.slots.default?.()}
      </button>
    )
  },
})
  • 理论上这里的 <button> 可以不加 onClick
    • 因为 <button> 是 BarButton 组件最外层的元素
    • 默认会自动继承 onClick 等所有属性
    • 但手动加上 onClick 的好处是可以在 onClick 里加更多自定义逻辑代码

vite 添加代理服务配置 ⇧

vite.config.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { fileURLToPath, pathToFileURL, URL } from 'node:url'
import { type ConfigEnv, type UserConfigExport,  defineConfig } from 'vite'
import { genViteConfigs } from './configs/genViteConfigs.ts'

// https://vite.dev/config/
export default defineConfig(({ command,}: ConfigEnv ) => ({
  // base: '/mangosteen-fe-0-publish/', // pnpm deploy --base='/mangosteen-fe-0-publish/'
  define: {
    __IS_DEV__: command === 'serve',
  },
  plugins: [
    ...genViteConfigs({ command, mode: process.env.NODE_ENV ?? 'development' }),
  ],
  server: {
    proxy: {
      '^/api/v1': {
        // 宿主机本地测试
        // target: 'http://localhost:3001',
        // target: 'http://127.0.0.1:3001',
        // 容器内部本地生测试
        // target: 'http://host.docker.internal:3001',
        // 云服务器(已在`/etc/hosts`中映射地址 server1)
        target: 'http://server1:3000',
        // target: 'http://182.92.225.245:3000',
        // changeOrigin: true,
        // rewrite: path => path,
      },
    },
  },
  resolve: {
    // ...
  },
  css: {
    // ...
  },
})) satisfies UserConfigExport
  • 代码里所有的 '^/api/v1' 开头的请求,都会被代理到 target 指定的地址
  • 直接请求当前 vite 项目启动的服务地址 http://localhost:5173/api/v1/validation_codes
  • 由 vite 启动的服务器代理转发请求,转发到:'^/api/v1': { target: 'xxx' }
    • 购买的云服务器地址 '^/api/v1': { target: 'http://server1:3000/' }
    • 从宿主机环境本地起的前端服务 '^/api/v1': { target: 'http://localhost:3000/' }
    • 从容器内部环境本地起的前端服务 '^/api/v1': { target: 'http://host.docker.internal:3000/' }
    • host.docker.internal 是 Docker 提供的一个特殊 DNS 名称(主机名)
    • 用于在容器内部解析并指向宿主机(运行 Docker 的物理机或虚拟机)的 IP 地址,方便容器内的应用连接宿主机上的服务。
    • 在容器里直接写 localhost 或 127.0.0.1 指向的是容器自己,而不是宿主机;
    • 用 host.docker.internal 则可以绕开手动查 IP 和 IP 变动的问题
    • 访问宿主机数据库或中间件:
      • 本地开发时,数据库(如 MySQL、Redis)跑在宿主机上,容器里的后端服务可以直接连 host.docker.internal:3306
    • 本地调试与反向代理:容器内的 Web 服务或 Nginx 需要把请求转发到宿主机正在调试的本地端口
      • (例如 http://docker.internal)
    • 跨网络中转:不同 Docker 网络下的服务若不方便直接打通,有时也会通过宿主机端口结合 host.docker.internal 中转
    • 多用于开发测试:生产环境更推荐通过规范的 Docker 网络、服务名或内网地址通信,而不是依赖宿主机网络

参考


成功和后端进行第一次联调 ⇧

安装 axios

1
pnpm add axios

引入 src/views/SignInView.tsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// import ...
import axios from 'axios'

export const SignInView = defineComponent({
  name: 'SignInView',
  setup(/* _props, _ctx */) {
    const formData = reactive({ email: '', validationCode: '' })
    const genOriginErrors = () => ({ email: [], validationCode: [] })
    const errors = reactive(genOriginErrors())
    const onSubmit = (e: SubmitEvent) => {
      e.preventDefault()
      Object.assign(errors, genOriginErrors())
      const newErrors = formValidate(formData, [
        { key: 'email', type: 'required', required: true, message: '必填' },
        {
          key: 'email',
          type: 'pattern',
          // /.+@.+/
          regexp: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
          message: '邮箱格式错误',
        },
        { key: 'validationCode', type: 'required', required: true, message: '必填' },
      ])
      Object.assign(errors, newErrors)
    }

    const sendValidationCode = async () => {
      const response = await axios.post(
        '/api/v1/validation_codes',
        { email: formData.email }
      )
      console.log('sendValidationCode_______________________')
      console.log(response)
      console.log('_______________________sendValidationCode')
    }
    return () => (
      <MainLayout>
        {{
          title: () => '登录',
          icon: () => <SvgIcon name="back-arrow" size="1.5em" />,
          default: () => (
            <div>
              <SignInBanner />

              <FormContainer onSubmit={onSubmit}>
                <FormItem
                  label="邮箱地址"
                  type="text"
                  v-model={formData.email}
                  hasErrorPlaceholder
                  placeholder="请输入邮箱,然后点击发送验证码"
                  error={errors.email?.join(',')}
                />
                <FormItem
                  label="验证码"
                  type="validationCode"
                  v-model={formData.validationCode}
                  onClick={sendValidationCode}
                  hasErrorPlaceholder
                  placeholder="请输入六位数字"
                  error={errors.validationCode?.join(',')}
                />
                <FormItem
                  type="submit"
                  buttonConfig={{ text: '登录' }}
                  class={cn('mt-2em')} />
              </FormContainer>
            </div>
          ),
        }}
      </MainLayout>
    )
  },
})
  • 测试本地俯后端服务和云服务器后端服务都通过,成功返回 200
  • 成功和后端进行第一次联调接口 /api/v1/validation_codes

由于单元测试没有测试第三方的邮件服务,目前邮件发送失败,接下来修改后端代码

3. 后端:修复邮件发送功能 ⇧

修改 app/models/validation_code.rb

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class ValidationCode < ApplicationRecord
  # email必填
  validates :email, presence: true
  # 钩子函数
  before_create :generate_code
  # 保存成功后执行
  after_create :send_email

  enum :kind, { sign_in: 0, reset_password: 1 }

  # 生成验证码.
  # @return [Object]
  def generate_code
    self.code = SecureRandom.random_number.to_s[2..7]
  end

  # 发送邮件.
  #
  # @return [Object]
  def send_email
    UserMailer.welcome_email(self.email).deliver_now
  end
end
  • .deliver_now 方法没有调用,漏写了 UserMailer.welcome_email(self.email).deliver_now

为配置生产环境的 SMTP 配置,在 config/environments/production.rb 中添加如下代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Rails.application.configure do
  # ...
  config.action_mailer.perform_caching = false
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:         "smtp.qq.com",
    port:            587,
    domain:          "smtp.qq.com",
    user_name:       "youremail@qq.com",
    password:        Rails.application.credentials.email_password,
    authentication:  "plain",
    enable_starttls: true,
    open_timeout:    10,
    read_timeout:    10 }
end
# ...
  • Rails.application.credentials.email_password 密钥目前只在开发环境配置,还需要以下配置生产密钥

在生产环境密钥中添加 email_password,解开 config/credentials/production.yml

  • 运行 VISUAL="code --wait" bin/rails credentials:edit --environment production
  • 内容可以从开发环境抄来 VISUAL="code --wait" bin/rails credentials:edit
  • 添加完成后,确保关闭当前打开的解开状态的密钥文件,才会保存
  • 确保 git 变更中有 config/credentials/production.yml 文件,并提交到 Git
  • 也可以重新生成密钥文件,并添加密钥

    1
    2
    3
    
    secret_key_base: xxx
    email_password: xxx
    hmac_secret: yyy
  • 这时可以重新运行部署脚本了

  • 部署本地宿主环境 bin/pack_for_host.sh,宿主机运行 RAILS_MASTER_KEY=xxx mangosteen_deploy/setup_host.sh

  • 部署远程云服务器环境 bin/pack_for_remote.sh


4. 前端:实现倒计时 ⇧


5. 前端:父组件调用子组件的函数 ⇧


6. $3 ⇧


·未完待续·

参考文章

后端注意,拿到代码后,可能需要 重新创建密钥: 。

  • 这一步是可选的,但如果你遇到 ActiveSupport::MessageEncryptor::InvalidMessage 报错,那么你就必须重新创建密钥了

相关文章

  • 无

  • 作者: Joel
  • 文章链接:
  • 版权声明
  • 非自由转载-非商用-非衍生-保持署名