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

Node.js调用Instagram API获取Access Token时遇400错误,是否语法有误?

解决Instagram OAuth获取Access Token的400错误问题

Hey there! Let's break down why you're hitting that 400 Bad Request error when trying to get an Instagram access token. Your code has a couple of small issues that are causing the syntax error:

问题分析

  • 错误的表单格式:Instagram的OAuth access_token接口要求数据以application/x-www-form-urlencoded格式发送,但你用了formData参数,这会让请求以multipart/form-data格式提交(这个格式是用来上传文件的,不适合普通表单字段)。
  • 多余的JSON解析:你在请求选项里设置了json: true,这会自动把响应体解析成JavaScript对象,之后再调用JSON.parse(body)反而会报错,因为body已经不是字符串了。
  • 拼写错误:你的client_secret字段拼写有误(写成了thelcientsecret,正确应该是theclientsecret——虽然这可能只是你示例里的笔误,但实际代码里一定要检查)。

修正后的代码

const request = require('request');

var formData = {
  client_id: "theclientid",
  client_secret: "theclientsecret", // 修正拼写错误
  grant_type: "authorization_code",
  redirect_uri: "http://localhost:3000/",
  code: "thecode"
};

// 用form替代formData,移除多余的JSON.parse
request.post({ 
  uri: "https://api.instagram.com/oauth/access_token", 
  form: formData, // 从formData改为form
  json: true 
}, function(err, res, body) {
  console.log(err);
  console.log(res.statusCode);
  
  if (!err && res.statusCode === 200) {
    console.log(body); // body已经被自动解析,无需JSON.parse
  } else {
    // 打印错误响应体,看看Instagram具体报错内容
    console.log("错误详情:", body);
  }
});

额外提示

如果改完之后还是报错,记得在错误分支里打印body——Instagram通常会返回详细的错误说明(比如客户端ID无效、授权码过期等),能帮你更快定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:05:37