request 작성

해결됨
김건훈 프로필

https://developers.kakao.com/docs/restapi/tool#user-api#/v1/user/unlink

저 곳 설명에 의하면 https://kapi.kakao.com/v1/user/unlink 로 헤더에 Authorization: Bearer 4S4XZfAsIZ1RFqr9bwWc2N0-qK-lW3ocUMIZUQorDKYAAAFugtugRw 내용을 담아 request요청을 보내라고 하여

 if (req.user.dataValues.provider == 'kakao'){
        let option = {
            uri: 'http://kapi.kakao.com/v1/user/unlink',
            method: 'POST',
            headers: `Authorization: Bearer ${req.user.dataValues.token}`,
        }
        requset(option, (error, respons, body) => {
            if (error){
                console.error(error);
                return next(error);
            } else {
                console.log("카톡 리퀘스트로 됨!!");
                req.logout();
                req.session.destroy();
                res.redirect('/'); 
            }
        });
    } else{
        console.log("logout OK"+req.user.dataValues.token);
        req.logout();
        req.session.destroy();
        res.redirect('/');   
    }   

이렇게 작성했으나 보내지지 않았습니다 ㅠㅠ 혹시 request에 헤더를 넣어 보내는 법을 알려주실 수 있나요?

조현영 프로필
조현영 23일 전

request 쓰지 마시고 axios 사용하시는 게 더 편리합니다.

axios.post(URI, {}, { headers: { 'Autho...': 'Bear ...' } }).then().catch();

김건훈 프로필
김건훈 23일 전
if (req.user.dataValues.provider == 'kakao'){
        axios.post('http://kapi.kakao.com/v1/user/unlink', {}, { headers: { 'Authorization': `Bearer ${req.user.dataValues.token}` }})
            .then((response) => {
                console.log("!!!!!!!!!!!!!!!!!!!!!!!!AXIOS logout OK");
                req.logout();
                req.session.destroy();
                res.redirect('/');   
            })
            .catch((error) => {
                console.error(error);
                return next(error);
            });
    } else{
        console.log("logout OK");
        req.logout();
        req.session.destroy();
        res.redirect('/');   
    }    
})

Error: Request failed with status code 404
    at createError (D:\Study\Server\nodejs\nodejsLib\login\node_modules\axios\lib\core\createError.js:16:15)
    at settle (D:\Study\Server\nodejs\nodejsLib\login\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (D:\Study\Server\nodejs\nodejsLib\login\node_modules\axios\lib\adapters\http.js:237:11)
    at IncomingMessage.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1198:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  config: {
    url: 'http://kapi.kakao.com/v1/user/logout',
    method: 'post',
    data: '{}',
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json;charset=utf-8',
      Authorization: 'Bearer wIJoCW23LVAvEfjZH7mjsUt32jV8XjI7QQrKXgo9dRoAAAFug9Tyiw',
      'User-Agent': 'axios/0.19.0',
      'Content-Length': 2
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    validateStatus: [Function: validateStatus]
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      socket: [Function (anonymous)],
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      error: [Function (anonymous)],
      timeout: [Function (anonymous)],
      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: Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'kapi.kakao.com',
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: false,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(asyncId)]: 283,
      [Symbol(kHandle)]: [TCP],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    },
    _header: 'POST /v1/user/logout HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: application/json;charset=utf-8\r\n' +
      'Authorization: Bearer wIJoCW23LVAvEfjZH7mjsUt32jV8XjI7QQrKXgo9dRoAAAFug9Tyiw\r\n' +
      'User-Agent: axios/0.19.0\r\n' +
      'Content-Length: 2\r\n' +
      'Host: kapi.kakao.com\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _onPendingData: [Function: noopPendingOutput],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      defaultPort: 80,
      protocol: 'http:',
      options: [Object],
      requests: {},
      sockets: [Object],
      freeSockets: {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256
    },
    socketPath: undefined,
    method: 'POST',
    path: '/v1/user/logout',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      readable: false,
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      socket: [Socket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      headers: [Object],
      rawHeaders: [Array],
      trailers: {},
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 404,
      statusMessage: 'Not Found',
      client: [Socket],
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'http://kapi.kakao.com/v1/user/logout',
      redirects: []
    },
    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: 2,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'http://kapi.kakao.com/v1/user/logout'
    },
    [Symbol(kNeedDrain)]: false,
    [Symbol(isCorked)]: false,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      authorization: [Array],
      'user-agent': [Array],
      'content-length': [Array],
      host: [Array]
    }
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      date: 'Tue, 19 Nov 2019 13:23:22 GMT',
      server: 'Apache',
      'content-length': '3',
      connection: 'close',
      'content-type': 'text/html; charset=iso-8859-1'
    },
    config: {
      url: 'http://kapi.kakao.com/v1/user/logout',
      method: 'post',
      data: '{}',
      headers: [Object],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      validateStatus: [Function: validateStatus]
    },
    request: <ref *1> 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: [Socket],
      _header: 'POST /v1/user/logout HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json;charset=utf-8\r\n' +
        'Authorization: Bearer wIJoCW23LVAvEfjZH7mjsUt32jV8XjI7QQrKXgo9dRoAAAFug9Tyiw\r\n' +
        'User-Agent: axios/0.19.0\r\n' +
        'Content-Length: 2\r\n' +
        'Host: kapi.kakao.com\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      path: '/v1/user/logout',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      _redirectable: [Writable],
      [Symbol(kNeedDrain)]: false,
      [Symbol(isCorked)]: false,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    data: 404
  },
  isAxiosError: true,
  toJSON: [Function (anonymous)]
}

이런 에러가 발생합니다...

조현영 프로필
조현영 23일 전

404에러인데 보통 주소가 틀렸을 때 발생하는 에러입니다.

지식공유자 되기
많은 사람들에게 배움의 기회를 주고,
경제적 보상을 받아보세요.
지식공유참여
기업 교육을 위한 인프런
“인프런 비즈니스” 를 통해 모든 팀원이 인프런의 강의들을
자유롭게 학습하는 환경을 제공하세요.
인프런 비즈니스