使用Twitter API创建媒体元数据时遇401认证错误(错误码32)求助
Twitter API 401认证错误(错误码32)排查方案
我正在开发一个可发布图文推文的Node.js程序,但在创建媒体元数据时遇到Twitter认证失败错误,返回信息为"Could not authenticate you.",错误码32,状态码401。以下是我的代码及错误响应:
代码实现
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1; const twit = require('twit'); const ApiKey ="API"; const ApiSecret = "API SECRET"; const AccessToken = "TOKEN"; const AccessTokenSecret = "TOKEN SECRET"; const fs = require("fs"); const files = ['FxCvZrAXgAUFXGS.png']; const status = 'Mrn'; const T = new twit({ consumer_key:ApiKey, consumer_secret:ApiSecret, access_token:AccessToken, access_token_secret:AccessTokenSecret, timeout_ms:60*1000, strictSSL:true, }); //run the test function function runpost(img, title){ try{ var b64content = fs.readFileSync(img, { encoding: 'base64' }); T.post('media/upload', { media_data: b64content }, function (err, data, response) { // now we can assign alt text to the media, for use by screen readers and // other text-based presentations and interpreters var mediaIdStr = data.media_id_string; var altText = title; var meta_params = {media_id: mediaIdStr, alt_text: { text: altText }}; T.post('media/metadata/create', meta_params, function (err, data, response) { if(err) throw err; // now we can reference the media and post a tweet (media will attach to the tweet) var params = { status: `${title}`, media_ids: [mediaIdStr] } T.post('statuses/update', params, function (err, data, response) { console.log(data); }); }); }); } catch(e){console.log(`The error is: ${e}`);} } runpost(`IMAGE_PATH/${files[0]}`, "Hello! Twitter");
错误响应
{ statusCode: 401, twitterReply: '{"errors":[{"code":32,"message":"Could not authenticate you."}]}', code: 32, allErrors: [ { code: 32, message: 'Could not authenticate you.' } ] }
排查与解决建议
- 核对认证信息准确性:确保
ApiKey、ApiSecret、AccessToken、AccessTokenSecret是从Twitter开发者平台完整复制的,无空格、拼写错误或大小写偏差。 - 检查应用权限:登录Twitter开发者后台,确认你的应用权限设置为
Read and write,只读权限无法发布内容或操作媒体元数据。 - 重置访问令牌:若令牌已过期或被撤销,在开发者后台重新生成新的访问令牌和令牌密钥,替换代码中的对应值。
- 调整TLS设置:移除
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1这行代码,强制关闭TLS验证可能导致认证请求被拦截,使用默认的SSL验证即可。 - 测试基础认证:先调用
account/verify_credentials接口验证认证是否有效,排除媒体上传流程的干扰,示例代码:T.get('account/verify_credentials', { skip_status: true }, function(err, data, response) { if (err) console.log(err); else console.log('认证成功:', data.screen_name); });
内容的提问来源于stack exchange,提问作者Deogratius Mabima
相关产品推荐
相关产品推荐

