收到对 Twitter 请求令牌端点的错误请求和对创建推文端点的无效请求?

Getting bad request for twitter request token endpoint and invalid request for create tweet endpoint?

我正在尝试代表用户发出请求,因此我已成功生成 oauth_access_token 和 oauth_access_token_secret 但每当我调用推文时 https://api.twitter.com/2/tweets

它给出了以下错误信息:post daata {"errors":[{"parameters":{},"message":"Requests with bodies must have content-type of application/json."}],"title":"Invalid Request","detail":"One or more parameters to your request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}

代码: oauth.js:

const OAuth = require('oauth');

module.exports = (oauthCallback) => {
  const TWITTER_CONSUMER_KEY = process.env.TWITTER_CONSUMER_KEY;
  const TWITTER_CONSUMER_SECRET = process.env.TWITTER_CONSUMER_SECRET;
  const twitter_request_token_url = 'https://api.twitter.com/oauth/request_token';
  const twitter_access_token_url = 'https://api.twitter.com/oauth/access_token';

  const _oauth = new OAuth.OAuth(
    twitter_request_token_url,
    twitter_access_token_url,
    TWITTER_CONSUMER_KEY, // consumer key
    TWITTER_CONSUMER_SECRET, // consumer secret
    "1.0",
    oauthCallback,
    "HMAC-SHA1"
  );

  const oauth = {
    post: (url, oauth_access_token, oauth_access_token_secret, post_body, post_content_type) => {
      return new Promise((resolve, reject) => {
        _oauth.post(url, oauth_access_token, oauth_access_token_secret, post_body, post_content_type,
          (error, data, response) => {
            console.log("post daata", data)
            console.log("post response", response)
            if (error) {
              reject(error);
            } else {
              resolve({ data, response });
            }
          }
        );
      });
    }
};

  return oauth;
};

route.js:

router.post('/twitter/tweet', async (req, res) => { 
try { 
const { response } = await oauth.post('https://api.twitter.com/2/tweets', oauth_access_token, oauth_access_token_secret, { "text": "Hello World!" }, 'application/json')

        console.log("response backend data", response.data);

        res.status(201).send({ message: "Tweet successful" });
    } catch (error) {
        res.status(403).json({ message: "Missing, invalid, or expired tokens" });
    }
});

我认为 node-oauth 包(FYR:https://github.com/ciaranj/node-oauth/issues/364#issue-1076029771)有一些问题,所以我切换到 oauth1a 但随后我收到 400 个请求令牌端点的错误请求 代码:

const crypto = require('crypto');
const OAuth = require('oauth-1.0a');
const axios = require('axios');

router.post('/twitter/oauth/request_token', async (req, res) => {
    try {
        const oauth = OAuth({
            consumer: {
                key: process.env.TWITTER_CONSUMER_KEY,
                secret: process.env.TWITTER_CONSUMER_SECRET
            },
            signature_method: 'HMAC-SHA1',
            hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
        });

        const authHeader = oauth.toHeader(oauth.authorize({
            url: `https://api.twitter.com/oauth/request_token?oauth_callback=http://localhost:3000`,
            method: 'POST'
        }));

        console.log("authHeader", authHeader)

        const response = await axios.post(`https://api.twitter.com/oauth/request_token?oauth_callback=http://localhost:3000`, {
            headers: {
                Authorization: authHeader["Authorization"]
            }
        });

        console.log("response", response)

        res.status(200).send({ status: "ok" });
    } catch (error) {
        console.log("error", error)
        res.status(404).json({
            message: "Twitter request token failed",
        });
    }
});

不确定此问题是否特定于 node-oauth 但使用 axios 我能够使用 twitter v2 API 发推文。添加的工作代码片段以供参考:

const express = require('express');
const router = express.Router();
const OAuth = require('oauth-1.0a');
const axios = require('axios');


router.post('/twitter/tweet', async (req, res) => {
    try {
        const oauth = OAuth({
            consumer: {
                key: process.env.TWITTER_CONSUMER_KEY,
                secret: process.env.TWITTER_CONSUMER_SECRET
            },
            signature_method: 'HMAC-SHA1',
            hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
        });

        const token = {
            key: '',
            secret: ''
        };

        const authHeader = oauth.toHeader(oauth.authorize({
            url: 'https://api.twitter.com/2/tweets',
            method: 'POST'
        }, token));

        const data = { "text": "Hello world!!" };

        await axios.post('https://api.twitter.com/2/tweets',
            data,
            {
                headers: {
                    Authorization: authHeader["Authorization"],
                    'user-agent': "v2CreateTweetJS",
                    'content-type': "application/json",
                    'accept': "application/json"
                }
            }
        );

        res.status(201).send({ message: "Tweet successful" });
    } catch (error) {
        console.log("error", error)
        res.status(403).send({ message: "Missing, invalid, or expired tokens" });
    }
});