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

如何在单个文件中编写多端点New Relic合成API测试

在New Relic监控脚本中添加多端点测试的实现方案

完全可以在同一个文件中添加多个API端点的测试,也支持通过构建配置数组循环调用的方式实现批量测试,以下是具体实现示例:

基础多端点实现

如果只是需要逐个添加端点测试,可直接多次调用request方法:

var request = require('request');

// 第一个端点测试
var options1 = {
  'method': 'GET',
  'url': 'https://test.api.endpoint.com/v1/test',
  'headers': {
    'x-api-key': 'apikey'
  }
};
request(options1, function (error, response) {
  if (error) throw new Error(error);
  console.log('端点1响应:', response.body);
});

// 第二个端点测试
var options2 = {
  'method': 'POST',
  'url': 'https://test.api.endpoint.com/v1/create',
  'headers': {
    'x-api-key': 'apikey',
    'Content-Type': 'application/json'
  },
  'body': JSON.stringify({"name": "test"})
};
request(options2, function (error, response) {
  if (error) throw new Error(error);
  console.log('端点2响应:', response.body);
});

数组循环批量实现

如果端点数量较多,推荐用配置数组循环处理,更易维护:

var request = require('request');

// 定义所有需要测试的端点配置数组
var endpoints = [
  {
    'method': 'GET',
    'url': 'https://test.api.endpoint.com/v1/test',
    'headers': {
      'x-api-key': 'apikey'
    },
    'label': '测试端点1'
  },
  {
    'method': 'GET',
    'url': 'https://test.api.endpoint.com/v1/health',
    'headers': {
      'x-api-key': 'apikey'
    },
    'label': '健康检查端点'
  },
  {
    'method': 'POST',
    'url': 'https://test.api.endpoint.com/v1/data',
    'headers': {
      'x-api-key': 'apikey',
      'Content-Type': 'application/json'
    },
    'body': JSON.stringify({"data": "sample"}),
    'label': '数据提交端点'
  }
];

// 循环遍历配置数组,发起请求
endpoints.forEach(function(endpoint) {
  // 复制配置,避免引用问题
  var options = {...endpoint};
  // 移除自定义label,避免干扰request参数
  delete options.label;
  
  request(options, function (error, response) {
    if (error) {
      console.error(`${endpoint.label}测试失败:`, error.message);
      throw new Error(error);
    }
    console.log(`${endpoint.label}测试成功,响应:`, response.body);
  });
});

注意事项

  • 每个请求的错误处理要独立,避免单个端点失败导致整个监控脚本终止
  • 如果需要确保请求按顺序执行,可以使用Promise或者async/await(需将request包装为Promise)
  • New Relic会捕获脚本中的日志和错误,确保每个端点的测试结果都有明确日志输出,方便后续排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 07:27:54