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

Axios GET请求二次调用失败,寻求排查解决方法

重复请求API时第二次总是返回404,Postman中正常

问题现象

  • 调用带分页机制的API,首次请求必然成功,但第二次请求无论访问哪个页面(包括重复请求同一页)都会返回404错误
  • 重启应用后首次请求恢复正常,但二次请求依旧失败
  • 所有请求在Postman中均可正常执行
  • 已尝试Axios、unirest、request及原生请求方式,使用的都是Postman生成的代码片段,示例代码如下:
var axios = require('axios');

const runScrape = () => {
    return new Promise(((resolve, reject) => {
        const api = axios.create()
        var config = {
            method: 'get',
            url: 'https://foo.bar/?page=1',
        };

        api(config)
            .then(function (response) {
                resolve("worked")
            })
            .catch(function (error) {
                reject("failed")
            });

    }))
}

runScrape().then(d => {
    console.log(d)
    runScrape().then(d => {
        console.log(d)
    }).catch(e => console.log(e))
}).catch(e => console.log(e))

可能的解决方案

1. 复刻Postman的完整请求头

Postman会自动携带一些默认请求头(比如User-Agent、Accept、Cookie等),代码中如果遗漏这些,可能被API服务端识别为非法请求。建议把Postman中的所有请求头完全复制到代码里:

var config = {
    method: 'get',
    url: 'https://foo.bar/?page=1',
    headers: {
        'User-Agent': 'PostmanRuntime/7.32.3', // 替换成你Postman里的User-Agent
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        // 如果Postman请求中有Cookie字段,也一并添加
    }
};

2. 复用请求实例以保持会话状态

每次调用runScrape都新建Axios实例,会导致首次请求获取的会话Cookie无法被二次请求携带。可以把Axios实例提取到函数外复用:

var axios = require('axios');
// 全局复用同一个Axios实例
const api = axios.create({
    headers: {
        // 提前配置好和Postman一致的请求头
    }
});

const runScrape = () => {
    return new Promise(((resolve, reject) => {
        var config = {
            method: 'get',
            url: 'https://foo.bar/?page=1',
        };

        api(config)
            .then(function (response) {
                resolve("worked")
            })
            .catch(function (error) {
                // 打印详细错误信息便于排查
                console.error('错误详情:', error.response?.data, error.response?.status);
                reject("failed")
            });

    }))
}

3. 检查API的反爬/会话限制

部分API会对同一来源的连续请求做限制,或者首次请求后标记会话,二次请求直接拦截。可以尝试在两次请求之间添加延迟:

runScrape().then(d => {
    console.log(d)
    // 延迟1秒再发起第二次请求
    setTimeout(() => {
        runScrape().then(d => console.log(d)).catch(e => console.log(e))
    }, 1000)
}).catch(e => console.log(e))

4. 打印完整错误信息定位问题

不要只返回"failed",把错误的响应状态码、响应内容、请求头都打印出来,能更快找到问题根源:

.catch(function (error) {
    console.error('请求失败详情:', {
        状态码: error.response?.status,
        响应内容: error.response?.data,
        请求头: error.config?.headers
    });
    reject("failed")
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:20:37