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

如何按序调用Axios函数、实现动态ID及修复请求与自定义错误

解决方案

1. 实现顺序调用逻辑

修改server.js中的implementScheduling为异步函数,接收Express的req和res参数,先执行postSchedule,只有当它成功返回时,再调用triggerSchedule,同时处理请求参数和响应结果。

2. 修复postSchedule的Bad Request错误

原错误是因为axios.post的参数顺序错误:Axios的POST方法格式为axios.post(url, data, config),原代码把headers配置放在了data参数的位置,导致请求体格式不符合接口要求,调整参数顺序即可修复。

3. 实现triggerSchedule的动态id传入

让triggerSchedule接收id作为参数,在Express路由中从请求的req.body或req.params中获取用户通过Postman传入的id,再传递给该函数。

4. 优化Promise与错误处理

修改functions.js中的函数,在捕获错误时抛出错误而非仅打印日志,这样Express后端可以捕获错误并返回给前端,前端就能根据返回的错误信息实现自定义业务逻辑。


修改后的functions.js

const axios = require("axios");
const BASE_URL = "http://localhost:8880";
const body = require("./payload.json");

// 修复postSchedule:调整Axios参数顺序,正确处理响应与错误抛出
const postSchedule = async () => {
  const headers = {
    "BKK-API-Version": "v2",
    "Content-type": "application/json",
  };
  const payload = body;
  try {
    // Axios.post正确参数顺序:URL、请求体、配置项(含headers)
    const resp = await axios.post(`${BASE_URL}/schedule`, payload, { headers });
    const data = resp.data;
    if (!data) {
      throw new Error("未能成功发送调度请求");
    }
    return data;
  } catch (err) {
    // 抛出错误给上层调用处理
    throw new Error(`postSchedule失败: ${err.message}`);
  }
};

// 修改triggerSchedule:接收id参数,修复响应变量名错误
const triggerSchedule = async (id) => {
  const headers = {
    "Content-type": "application/json",
  };
  try {
    // 拼接动态id到URL
    const resp = await axios.post(`${BASE_URL}/schedule/${id}`, {}, { headers });
    if (resp.status === 200) {
      console.log("调度已成功触发", resp.data);
    }
    return resp.data;
  } catch (e) {
    throw new Error(`triggerSchedule失败: ${e.message}`);
  }
};

module.exports = {
  triggerSchedule,
  postSchedule,
};

修改后的server.js

// 依赖
const express = require("express");
const schedules = require("./functions.js"); // 修复原导入路径拼写错误(function.js → functions.js)
const cors = require("cors");
const app = express();
app.use(cors());
const PORT = 8000;
app.use(express.json());

app.listen(PORT, () => {
  console.log(`服务运行在端口 ${PORT}`);
});

// 改为异步函数,接收req和res处理请求与响应
const implementScheduling = async (req, res) => {
  try {
    // 1. 执行postSchedule请求
    const postResult = await schedules.postSchedule();
    console.log("postSchedule执行成功", postResult);

    // 2. 获取用户传入的id(示例从req.body获取,若用URL参数可改为req.params.id)
    const scheduleId = req.body.id;
    if (!scheduleId) {
      return res.status(400).json({ error: "缺少必要参数id" });
    }

    // 3. postSchedule成功后,执行triggerSchedule
    const triggerResult = await schedules.triggerSchedule(scheduleId);
    
    // 返回成功响应给前端
    return res.status(200).json({
      message: "调度流程执行完成",
      postScheduleResult: postResult,
      triggerScheduleResult: triggerResult
    });
  } catch (err) {
    // 捕获错误并返回给前端
    return res.status(500).json({ error: err.message });
  }
};

// 改为POST路由(匹配前端请求方式),传递函数引用而非直接调用
app.post("/schedule", implementScheduling);

修改后的前端代码(优化错误处理)

const setSchedule = () => {
  const body = payload; // 确保payload已提前定义

  axios
    .post("http://localhost:8000/schedule", body)
    .then((resp) => {
      const data = resp.data;
      saveSchedule(scheduleResponse, data);
      console.log("调度流程执行成功", data);
      // 可添加更多成功后的业务逻辑
    })
    .catch((err) => {
      // 自定义错误处理
      if (err.response) {
        // 后端返回的错误信息
        console.error("请求失败:", err.response.data.error);
        // 示例:添加UI提示
        // alert(`操作失败:${err.response.data.error}`);
      } else {
        // 网络或请求配置错误
        console.error("网络错误:", err.message);
      }
    });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:05:17