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

NodeJS自动发送POST请求异常排查:代码无输出如何解决?

NodeJS定时发送POST请求无控制台输出问题排查

问题描述

尝试实现NodeJS应用每2分钟自动发送POST请求,但编写的代码没有输出控制台日志,无法确认功能正常。通过POSTMAN测试目标POST请求可正常返回结果,代码如下:

'use strict';
const express = require('express');
const config = require('./config');
const cors = require('cors');
const bodyParser = require('body-parser');
const eventRoutes = require('./routes/eventRoutes')

const app = express();

app.use(cors());
app.use(bodyParser.json());


app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
});
  
app.get('/api', (req, res) => {
    request(
      { url: 'http://localhost:3507/api' },
      (error, response, body) => {
        if (error || response.statusCode !== 200) {
          return res.status(500).json({ type: 'error', message: err.message });
        }
  
        res.json(JSON.parse(body));
      }
    )
});
  

var minutes = 2, the_interval = minutes * 60 * 1000;
setInterval(function() {
  app.post('/api/add', (req, res) => {
    console.log('Post Request!');
    request(
      { url: 'http://localhost:3507/api/add' },
      (error, response, body) => {
        if (error || response.statusCode !== 200) {
          return res.status(500).json({ type: 'error', message: err.message });
        }
  
        res.json(JSON.parse(body));
      }
    )
  });
}, the_interval);

app.use('/api', eventRoutes.routes)

app.listen(config.port, () => console.log(`Server is listening on http://localhost:` + config.port))

问题排查与修正

1. 核心逻辑错误:定时器内重复注册路由而非发送请求

你在setInterval中执行的是注册Express路由的操作,而非主动发送POST请求。每次定时器触发,只是给Express新增一个/api/add的POST路由处理函数,但这个函数只有当外部向你的服务发起/api/add请求时才会执行,根本不会主动调用目标接口,所以console.log永远不会触发。

2. 缺失依赖模块,且使用已弃用工具

代码中使用了request函数,但顶部没有引入该模块,运行时会直接抛出request is not defined错误。另外request模块已被官方弃用,推荐使用axios或node-fetch替代。

3. 错误处理变量名不一致

在app.get('/api')和定时任务的错误分支中,你使用了err.message,但参数定义的是error,会导致err is not defined的报错。

修正后的代码示例

'use strict';
const express = require('express');
const config = require('./config');
const cors = require('cors');
const bodyParser = require('body-parser');
const eventRoutes = require('./routes/eventRoutes');
// 用axios替代已弃用的request模块
const axios = require('axios');

const app = express();

app.use(cors());
app.use(bodyParser.json());

// cors中间件已完成跨域设置,无需重复添加header
app.get('/api', async (req, res) => {
  try {
    const response = await axios.get('http://localhost:3507/api');
    res.json(response.data);
  } catch (error) {
    console.error('GET请求失败:', error.message);
    res.status(500).json({ type: 'error', message: error.message });
  }
});

// 定时发送POST请求的正确逻辑
const minutes = 2;
const interval = minutes * 60 * 1000;
setInterval(async () => {
  console.log('开始执行定时POST请求');
  try {
    const response = await axios.post('http://localhost:3507/api/add');
    console.log('POST请求成功,返回结果:', response.data);
  } catch (error) {
    console.error('POST请求失败:', error.message);
  }
}, interval);

app.use('/api', eventRoutes.routes);

app.listen(config.port, () => console.log(`Server is listening on http://localhost:${config.port}`));

修正说明

  • 移除重复的跨域配置,cors()中间件已足够处理跨域需求
  • 替换request为axios,使用async/await让异步逻辑更清晰易读
  • 将定时器内的路由注册逻辑改为主动发送POST请求的代码
  • 修正错误处理中的变量名不一致问题
  • 增加请求成功/失败的详细日志,便于调试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:36:24