智能简历平台Plus——前端数据保存至数据库(9)

概要

  • 实现方法要点
  • 前端——将数据传到后端
  • 后端——将数据保存至数据库
  • 数据库

实现方法要点

前端页面输入自己的信息到输入框里,一旦离开自己的输入框,数据便开始向后端传输,并保存在数据库里
每一个小组件分别实现这样的功能,以组件为单位,完成数据的传输与后端接收

前端

思路
`打印即将发送的数据:

  1. 在发送请求之前,将当前的表单数据 this.formData 打印到控制台。这有助于在调试过程中查看即将发送的数据是否正确。 发送
    POST 请求
  2. 使用 axios.post 方法向指定的服务器端点
    (http://127.0.0.1:5000/api/user_basic_info) 发送 POST 请求。 请求的负载是
    this.formData,即客户端需要发送到服务器的数据。 处理成功响应
  3. 如果服务器成功处理了请求,执行 then 回调函数: 打印服务器返回的成功信息到控制台。 更新客户端的表单数据 this.formData 为服务器返回的数据。这通常用于确保客户端和服务器端的数据保持一致。
  4. 处理错误响应:如果请求失败,执行 catch 回调函数:打印错误信息到控制台。如果服务器返回了详细的错误信息,则打印这些信息;否则,打印整个错误对象。这有助于调试和处理请求失败的情况。
    部分组件代码示例
    ProfileSection.vue
 saveData() {
      console.log('Payload:', this.formData); // 打印发送的数据

      axios.post('http://127.0.0.1:5000/api/user_basic_info', this.formData)
        .then(response => {
          console.log('Data saved successfully:', response.data);
          // 更新表单数据
          this.formData = response.data;
        })
        .catch(error => {
          console.error('Error saving data:', error.response ? error.response.data : error);
        });
    },

ResumeInformation.vue

 saveResumeName() {
      axios.post('http://127.0.0.1:5000/api/saveResumeName', { resume_name: this.resume_name })
        .then(response => {
          console.log('Resume name saved:', response.data);
        })
        .catch(error => {
          console.error('Error saving resume name:', error);
        });
    },

EducationBack.vue

saveData() {
      const payload = {
        school_name: this.educationForm.school_name,
        major: this.educationForm.major,
        readingTime_start: this.educationForm.studyTime[0],
        readingTime_end: this.educationForm.studyTime[1],
        educational_background: this.educationForm.educational_background,
        experience_details: this.educationForm.experience_details
      };

      axios.post('http://127.0.0.1:5000/api/education_info', payload)
        .then(response => {
          console.log('Data saved successfully:', response);
        })
        .catch(error => {
          console.error('Error saving data:', error.response ? error.response.data : error);
        });
    },

后端代码

`代码主要思路

  1. 定义路由和跨域设置:
    创建一个 POST 请求的 API 端点 /api/education_info。 允许来自 http://localhost:8080
    的跨域请求。 接收和验证请求数据:
  2. 从请求中获取 JSON 数据。
    检查请求数据是否包含所有必填字段(school_name、major、educational_background、experience_details),如果缺少任何字段,返回
    400 错误响应。 数据库操作:
  3. 获取数据库连接和创建游标。 暂时注释掉与学习时间相关的代码,因为当前不需要处理这些字段。 执行插入操作,将教育信息插入到
    user_details 表中。 提交事务并返回响应:
  4. 提交数据库事务,确保数据被保存。 返回成功响应,表示教育信息保存成功。 错误处理和资源释放:
  5. 捕获数据库操作中的错误并记录日志。 返回数据库错误响应。 确保在操作完成后关闭数据库连接,无论是否发生错误
    部分示例
@app.route('/api/education_info', methods=['POST'])
@cross_origin(origins='http://localhost:8080')  # 允许特定域名访问
def save_education_info():
    data = request.json

    # 检查必填字段
    required_fields = ['school_name', 'major', 'educational_background', 'experience_details']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'{field} is required'}), 400

    try:
        # 获取数据库连接
        conn = get_db_connection()
        cursor = conn.cursor()

        # 将学习时间部分代码暂时注释掉
        # readingTime_start, readingTime_end = data.get('studyTime', [None, None])

        # if not readingTime_start or not readingTime_end:
        #     return jsonify({'error': 'Both start and end dates are required for studyTime'}), 400

        # 执行插入操作,暂时不插入时间字段
        cursor.execute('''
            INSERT INTO user_details (school_name, major, educational_background, experience_details)
            VALUES (?, ?, ?, ?)
        ''', (data['school_name'], data['major'], data['educational_background'], data['experience_details']))

        # 提交事务
        conn.commit()

        return jsonify({'success': 'Education information saved successfully'}), 200
    except sqlite3.Error as e:
        logging.error(f'Database error: {e}')
        return jsonify({'error': 'Database error'}), 500
    finally:
        conn.close()
@app.route('/api/job_intention', methods=['POST'])
@cross_origin(origins='http://localhost:8080')  # 允许特定域名访问
def save_job_intention():
    data = request.json

    # 检查是否缺少必填字段
    required_fields = ['intention_position', 'intention_city', 'intention_salary', 'attend_time']
    for field in required_fields:
        if field not in data:
            logging.error(f'Missing required field: {field}')
            return jsonify({'error': f'{field} is required'}), 400

    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO user_details (intention_position, intention_city, intention_salary, attend_time)
            VALUES (?, ?, ?, ?)
        ''', (data['intention_position'], data['intention_city'], data['intention_salary'], data['attend_time']))
        conn.commit()
        logging.info('Job intention saved successfully')
    except sqlite3.Error as e:
        logging.error(f'Database error: {e}')
        return jsonify({'error': 'Database error'}), 500
    finally:
        conn.close()

    return jsonify({'message': 'Job intention saved successfully'}), 201
@app.route('/api/project_experience', methods=['POST'])
@cross_origin(origins='http://localhost:8080')
def save_project_experience():
    data = request.json

    # 检查必填字段
    required_fields = ['program_name', 'program_timeRole', 'program_experience']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'{field} is required'}), 400

    try:
        # 获取数据库连接
        conn = get_db_connection()
        cursor = conn.cursor()

        # 执行插入操作
        cursor.execute('''
            INSERT INTO user_details (program_name, program_timeRole, program_experience)
            VALUES (?, ?, ?)
        ''', (data['program_name'], data['program_timeRole'], data['program_experience']))

        # 提交事务
        conn.commit()

        return jsonify({'success': 'Project experience saved successfully'}), 200
    except sqlite3.Error as e:
        logging.error(f'Database error: {e}')
        return jsonify({'error': 'Database error'}), 500
    finally:
        conn.close()

数据库

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值