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

使用node-fetch时自定义Header未生效致API返回403的问题

Node-fetch自定义User-Agent不生效的解决办法

你这段代码的核心问题是fetch参数结构错误——你把包含method和headers的请求配置对象,错误地当成了URLSearchParams的第二个参数,而非fetch的第二个参数。这直接导致自定义的User-Agent根本没被添加到请求头里,所以API返回了IllegalUserAgent的403拒绝。

修正后的代码

import { default as fetch } from "node-fetch"

const headers = {
  'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15"
}

const WeatherAPI2 = async (lat, lon) => {
  await fetch(
    'https://api.met.no/weatherapi/locationforecast/2.0/compact?' + new URLSearchParams({
      'lat': lat,
      'lon': lon
      //'altitude': (altitude === null) ? '' : altitude
    }),
    {
      method: "GET",
      headers: headers
    }
  ).then((response) => {
    console.log(response)
  })
}

WeatherAPI2(60.10,9.58)

关键修正说明

  • 把URLSearchParams的括号正确闭合,将请求配置对象({method, headers})作为fetch的第二个独立参数传入,这样node-fetch才能识别并使用你定义的请求头。
  • 额外提示:GET请求通常不需要设置Content-Type(因为没有请求体),可以直接去掉这个冗余的头字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:15:40