首页 > 解决方案 > 上传到 Youtube API v3 时出现错误状态 400

问题描述

尝试发布到 Youtube v3 API 时,我不断收到错误消息。我正在尝试获取响应 URI,以便上传 Youtube 视频。

这是我引用的文档:https ://developers.google.com/youtube/v3/docs/videos/insert#go

有谁知道我做错了什么?错误日志如下。

我的代码:

axios({
    method: 'POST',
    baseURL: 'https://www.googleapis.com',
    url: '/upload/youtube/v3/videos',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Content-Length': 167,
        'X-Upload-Content-Length': 302080,
        'X-Upload-Content-Type': 'video/mp4',
        'Authorization': `Bearer <MY_ACCESS_TOKEN>`, // has my actual access_token
    },
    params: {
        'uploadType': 'resumable',
        'key': <MY_API_KEY>, // has my actual app API key
        'part': 'snippet,status'
    },
    data: {
        'snippet': {
            'title': 'Test Upload 1',
            'description': 'Test Description 1',
            'tags': ['tag1', 'tag2'],
        },
        'status': {
            'privacyStatus': 'private', 
        }
    }
})
.then(response => {
    res.json(response.data);
})
.catch(err => console.log(err));

错误日志:

Error: Request failed with status code 400
    at createError (/mnt/e/Dev/20200316_youtube_api/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/mnt/e/Dev/20200316_youtube_api/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/mnt/e/Dev/20200316_youtube_api/node_modules/axios/lib/adapters/http.js:236:11)
    at IncomingMessage.emit (events.js:323:22)
    at endReadableNT (_stream_readable.js:1204:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  config: {
    url: '/upload/youtube/v3/videos',
    method: 'post',
    params: {
      key: '<MY_API_KEY>',
      part: 'snippet,status'
    },
    data: '{"snippet":{"title":"Test Upload 1","description":"Test Description 1","tags":["tag1","tag2"]},"status":{"privacyStatus":"private"}}',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Content-Length': 132,
      'X-Upload-Content-Length': 302080,
      'X-Upload-Content-Type': 'video/mp4',
      Authorization: 'Bearer <MY_ACCESS_TOKEN>',
      'User-Agent': 'axios/0.19.2'
    },
    baseURL: 'https://www.googleapis.com',
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    validateStatus: [Function: validateStatus]
  },
  request: ClientRequest {
    _events: [Object: null prototype] {
      socket: [Function],
      abort: [Function],
      aborted: [Function],
      error: [Function],
      timeout: [Function],
      prefinish: [Function: requestOnPrefinish]
    },
    _eventsCount: 6,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: null,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      _SNICallback: null,
      servername: 'www.googleapis.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 9,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'www.googleapis.com',
      _readableState: [ReadableState],
      readable: true,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: false,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular],
      [Symbol(res)]: [TLSWrap],
      [Symbol(asyncId)]: 6,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    connection: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      _SNICallback: null,
      servername: 'www.googleapis.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 9,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'www.googleapis.com',
      _readableState: [ReadableState],
      readable: true,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: false,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular],
      [Symbol(res)]: [TLSWrap],
      [Symbol(asyncId)]: 6,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /upload/youtube/v3/videos?key=<MY_API_KEY>&part=snippet,status HTTP/1.1\r\n' +
      'Accept: application/json\r\n' +
      'Content-Type: application/json\r\n' +
      'Content-Length: 132\r\n' +
      'X-Upload-Content-Length: 302080\r\n' +
      'X-Upload-Content-Type: video/mp4\r\n' +
      'Authorization: Bearer <MY_ACCESS_TOKEN>\r\n' +
      'User-Agent: axios/0.19.2\r\n' +
      'Host: www.googleapis.com\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _onPendingData: [Function: noopPendingOutput],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object],
      requests: {},
      sockets: [Object],
      freeSockets: {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    insecureHTTPParser: undefined,
    path: '/upload/youtube/v3/videos?key=<MY_API_KEY>&part=snippet,status',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      readable: false,
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      socket: [TLSSocket],
      connection: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      headers: [Object],
      rawHeaders: [Array],
      trailers: {},
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 400,
      statusMessage: 'Bad Request',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular],
      responseUrl: 'https://www.googleapis.com/upload/youtube/v3/videos?key=<MY_API_KEY>&part=snippet,status', 
      redirects: [],
      [Symbol(kCapture)]: false
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    _redirectable: Writable {
      _writableState: [WritableState],
      writable: true,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _options: [Object],
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 132,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function],
      _currentRequest: [Circular],
      _currentUrl: 'https://www.googleapis.com/upload/youtube/v3/videos?key=<MY_API_KEY>&part=snippet,status', 
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      'content-length': [Array],
      'x-upload-content-length': [Array],
      'x-upload-content-type': [Array],
      authorization: [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {
    status: 400,
    statusText: 'Bad Request',
    headers: {
      'x-guploader-uploadid': '<REPONSE_ID_THAT_I_REMOVED>',
      vary: 'Origin, X-Origin',
      'content-type': 'application/json; charset=UTF-8',
      'content-length': '353',
      date: 'Sun, 07 Jun 2020 22:45:50 GMT',
      server: 'UploadServer',
      'alt-svc': 'h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; 
ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
      connection: 'close'
    },
    config: {
      url: '/upload/youtube/v3/videos',
      method: 'post',
      params: [Object],
      data: '{"snippet":{"title":"Test Upload 1","description":"Test Description 1","tags":["tag1","tag2"]},"status":{"privacyStatus":"private"}}',
      headers: [Object],
      baseURL: 'https://www.googleapis.com',
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      validateStatus: [Function: validateStatus]
    },
    request: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      connection: [TLSSocket],
      _header: 'POST /upload/youtube/v3/videos?key=<MY_API_KEY>&part=snippet,status HTTP/1.1\r\n' +
        'Accept: application/json\r\n' +
        'Content-Type: application/json\r\n' +
        'Content-Length: 132\r\n' +
        'X-Upload-Content-Length: 302080\r\n' +
        'X-Upload-Content-Type: video/mp4\r\n' +
        'Authorization: Bearer <MY_ACCESS_TOKEN>\r\n' +
        'User-Agent: axios/0.19.2\r\n' +
        'Host: www.googleapis.com\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      insecureHTTPParser: undefined,
      path: '/upload/youtube/v3/videos?key=<MY_API_KEY>&part=snippet,status',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function]
}

标签: postgoogle-apiyoutubeaxiosyoutube-api

解决方案


推荐阅读