You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中加密数据POST请求无法获取API响应问题排查

React POST请求加密数据问题排查

我正在学习ReactJS提升Web开发能力,已经完成CRUD应用等项目开发,此前成功从模拟API获取数据并实现了展示API数据的目录菜单。当前任务要求将数据通过指定密钥加密后发送POST请求至API并获取响应,但编写代码后既无法获取响应,也无法在控制台看到错误信息,怀疑请求发送或加密数据传递环节存在问题,以下是Login组件代码:

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";

import CryptoJS from "crypto-js";

import axios from "axios";

import "./login.css";


function Login() {

  const [mobile, setMobile] = useState("");
  const [pin, setPin] = useState("");
  const [accessToken, setAccessToken] = useState("");
  

  const navigate = useNavigate();


  const data = { user_mobile: mobile, user_pin : pin} 

  const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'tpcgkCABsh051409').toString();


  const handleSubmit = async (e) =>{
    e.preventDefault();
    console.log("form submitted")
    const data = { user_mobile: mobile, user_pin: pin };

    fetch("http://business.thesmartr.com/v1/authorization/login.php", {
      method: "POST",
      headers: {
        "access-control-allow-origin" : "*",
        "Content-Type": "application/json"
      },
      mode:"no-cors",
      body: ciphertext
    })
    .then(response => response.json)
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      console.error("Error:", error);
      alert(error.message);
    });
  }
  

  return (
    <div className="main-div">
      <div className="center">
        <div className="logo">
          <img src="/images/bizwy logo.svg"/>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="txt-field">
            <input
                type="number"
                value={mobile}
                onChange={(event) => setMobile(event.target.value)}
                required
              />
              <span></span>
            <label>Mobile Number</label>
          </div>
          <div className="txt-field">
            <input
                type="password"
                value={pin}
                onChange={(event) => setPin(event.target.value)}
                required
              />
              <span></span>
            <label>Password</label>
          </div>
          <div className="pass">Forgot Password</div>
          {/* <button type="submit">Login</button> */}
          <div className="submit">
            <input type="submit" value="Login"/>
          </div>
        </form>
      </div>
    </div>
  );
}

export default Login;

核心错误点及解决方法

  • mode: "no-cors"限制响应访问
    设置该模式后,浏览器会完全限制前端对响应内容的读取,即使API返回数据也无法获取,且不会抛出错误。直接删除mode:"no-cors"配置,确保API服务器已配置正确的CORS跨域头。

  • 加密时机错误
    当前ciphertext在组件初始化时计算,此时mobile和pin为空值,提交时使用的是初始空数据的加密结果。需将加密逻辑移至handleSubmit函数内部,确保使用最新的表单输入值:

    const handleSubmit = async (e) =>{
      e.preventDefault();
      console.log("form submitted")
      const data = { user_mobile: mobile, user_pin: pin };
      // 移到这里加密最新数据
      const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'tpcgkCABsh051409').toString();
      
      // 后续请求代码...
    }
    
  • response.json调用错误
    缺少函数调用括号,应改为response.json(),否则会将函数本身作为结果返回,无法解析响应JSON:

    .then(response => response.json())
    
  • 请求头与请求体不匹配
    设置了Content-Type: application/json,但请求体是加密后的字符串(非JSON格式)。两种修正方式:

    1. 将加密字符串包装为JSON对象:body: JSON.stringify({ encryptedData: ciphertext })
    2. 修改请求头为"Content-Type": "text/plain"(需确认API支持该格式)
  • 冗余代码清理
    组件顶部定义的data和ciphertext变量未在提交时使用,可直接删除,避免混淆。

修正后的handleSubmit示例

const handleSubmit = async (e) =>{
  e.preventDefault();
  console.log("form submitted")
  const data = { user_mobile: mobile, user_pin: pin };
  const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'tpcgkCABsh051409').toString();

  fetch("http://business.thesmartr.com/v1/authorization/login.php", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ encryptedData: ciphertext })
  })
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
    // 后续处理逻辑,比如存储token、跳转页面
  })
  .catch(error => {
    console.error("Error:", error);
    alert(error.message);
  });
}

内容的提问来源于stack exchange,提问作者dowoyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 04:30:42