尝试使用所有必需的参数获取Instagram访问令牌,但仍然得到错误代码400

时间:2018-06-06 16:42:53

标签: node.js http express

这是尝试向Instagram发出POST请求以获取访问令牌的服务器端代码

app.get('/instagram/json', (req, res) => {
    axios({
        method: 'post',
        url: 'https://api.instagram.com/oauth/access_token',
        data: {
            'client_id': instagramClientId,
            'client_secret': instagramClientSecret,
            'grant_type': 'authorization_code',
            'redirect_uri': 'http://localhost:3000',
            'code': instagramCode
        }
      }).then((response) => {
            console.log(response);
        }).catch((e) => {
              console.log(e);
          });
});

这是我得到的错误回复。它告诉我" client_id"虽然我已经提供了它,但仍然是必需的。

 data: 
  { error_type: 'OAuthException',
    code: 400,
    error_message: 'You must provide a client_id' } } }

3 个答案:

答案 0 :(得分:0)

后来,但是由于网络上没有一个好的答案,我花了一段时间:

在将其提供给fetch-node的帖子之前,您必须先将其包裹在表单数据中。

安装表单数据:npm install --save form-data 然后:

const formData = require("form-data");
const insta_form = new formData();
insta_form.append("client_id", your client id);
insta_form.append("client_secret", your client secret);
insta_form.append("grant_type", "authorization_code");
insta_form.append("redirect_uri", your redirect uri);
insta_form.append("code", user code);
const shortTokenRes = await fetch(
  "https://api.instagram.com/oauth/access_token",
  {
    method: "POST",
    body: insta_form,
  }
);

答案 1 :(得分:0)

这是一个解决方案:

const insta_form = new URLSearchParams();
  insta_form.append('client_id', 'xxx');
  insta_form.append('client_secret', 'xxx');
  insta_form.append('grant_type', 'authorization_code');
  insta_form.append('redirect_uri', 'xxx');
  insta_form.append(
    'code',
    'xxx'
  );

    await axios({
      method: 'POST',
      url: 'https://api.instagram.com/oauth/access_token',
      data: insta_form,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })
      .then((response) => {
        console.log(response);
        
      })
      .catch((err) => {
        console.log(err.response);
        
      });
  }

答案 2 :(得分:0)

  import axios from 'axios'
  import {stringify} from 'qs'

  const response = await axios({
    method: "post",
    url: "https://api.instagram.com/oauth/access_token",
    data: stringify({
      client_id: CLIENT_ID, 
      client_secret: CLIENT_SECRET, 
      grant_type: 'authorization_code', 
      redirect_uri: REDIRECT_URL, 
      code
    }),
    headers: { "Content-Type": 'application/x-www-form-urlencoded' },
  })