简体   繁体   中英

Is there a way I can call an API from an api in express the parameter value in axios is undefined how do i add parameters in axios from a variable

**I tried passing in a parameter to my route and then passing that parameter to the variable axios with the url. The request succeeds if I remove the params object and instead hardcode the parameter in the url.

I am trying to post the question, but my word is little and the code is too much. I don't know how I can solve this so the explanation is enough to solve the question. I have explained it to the best of my ability. the code can tell much for itself. Thank you.

const axios = require("axios");
dotenv.config();
const Url = "https://api.dhl.com/location-finder/v1/find-by-address";
exports.getLocation = (req, res, next) => {
  const country = req.body.countryCode;
  axios
    .get(Url, {
      params: {
        countryCode: country}
      ,headers: {'DHL-API-Key': process.env.LOCATOR_API_KEY}})
    .then(function (response) {
      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
};```
//CODE CONSOLE LOG
**THIS IS THE CONSOLE LOG THE PARAMETER PART IS UNDEFINED HOW WILL I ADD THE PARAMETER

Error: Request failed with status code 400
    at createError (/media/ALWI/HACKERFOREVER/MyProjects/JULEYBIB_SHIPPING/server/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/media/ALWI/HACKERFOREVER/MyProjects/JULEYBIB_SHIPPING/server/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/media/ALWI/HACKERFOREVER/MyProjects/JULEYBIB_SHIPPING/server/node_modules/axios/lib/adapters/http.js:236:11)
    at IncomingMessage.emit (events.js:322:22)
    at endReadableNT (_stream_readable.js:1187:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  config: {
    url: 'https://api.dhl.com/location-finder/v1/find-by-address',
    method: 'get',
    params: { countryCode: undefined },
    headers: {
      Accept: 'application/json, text/plain, */*',
      'DHL-API-Key': '**********************',
      'User-Agent': 'axios/0.19.2'
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    validateStatus: [Function: validateStatus],
    data: undefined
  },
  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: false,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: 0,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      _SNICallback: null,
      servername: 'api.dhl.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 9,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.dhl.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)]: 301,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: false,
      [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: 'api.dhl.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 9,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.dhl.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)]: 301,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: false,
      [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: 'GET /location-finder/v1/find-by-address HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'DHL-API-Key: *********************\r\n' +
      'User-Agent: axios/0.19.2\r\n' +
      'Host: api.dhl.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: 'GET',
    insecureHTTPParser: undefined,
    path: '/location-finder/v1/find-by-address',
    _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://api.dhl.com/location-finder/v1/find-by-address',
      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: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function],
      _currentRequest: [Circular],
      _currentUrl: 'https://api.dhl.com/location-finder/v1/find-by-address',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'dhl-api-key': [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new

    status: 400,
    statusText: 'Bad Request',
    headers: {
      date: 'Mon, 04 May 2020 09:02:52 GMT',
      'content-type': 'application/json',
      'content-length': '71',
      connection: 'close',
      'access-control-allow-origin': '*',
      'access-control-allow-headers': 'origin,x-requested-with,accept,accept-encoding,content-type,dhl-api-key',
      'access-control-max-age': '3628800',
      'access-control-allow-methods': 'GET,OPTIONS',
      'correlation-id': 'f10a4f9b-0538-4dd5-bdc0-9069f90558ad'
    },
    config: {
      url: 'https://api.dhl.com/location-finder/v1/find-by-address',
      method: 'get',
      params: [Object],
      headers: [Object],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit newTOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      validateStatus: [Function: validateStatus],
      data: undefined
    },
**I tried passing in a parameter to my route and then pass the parameter to a variable the the variable to axios with the uri the requests succeeds if i remove the params object and if i hardcode the parameter in the url help me solve the parameter problem i am abit new
    request: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      connection: [TLSSocket],
      _header: 'GET /location-finder/v1/find-by-address HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'DHL-API-Key: ****************************\r\n' +
        'User-Agent: axios/0.19.2\r\n' +
        'Host: api.dhl.com\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      insecureHTTPParser: undefined,
      path: '/location-finder/v1/find-by-address',
      _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]


}

It is a breaking change from axios version 0.19. If you would like to add a parameter to a request you have to pass it via an interceptor. As example:

const axios = require('axios');
// api openexchange
const oexchange = axios.create({
  baseURL: 'https://openexchangerates.org/api/',
  timeout: parseInt(process.env.TIMEOUTEXTERNALREQUEST)
})
oexchange.interceptors.request.use((config) => {
  config.params = config.params || {};
  config.params.app_id = process.env.OPENEXCHANGEAPITOKEN // <-- here add the query params in your case it will be countryCode
  return config;
});

exports.cotacao = async (req, res) => {
  try {
    req.oexchange = await oexchange.get('latest.json') //here i'm calling external api with query params added in interceptor
    return res.status(200).json(req.oexchange.data)
  } catch (e) {
    res.status(500).json({errors: [{ location: 'cotacao', msg: 'Houve um erro ao acessar a api do open exchange.', param: 'openexchangerates' }]})
  }
}

It is a know behavior that was added in version 0.19 (May 30, 2019) Currently there is a community effort to fix that behavior you can follow here , it is addressed to be fixed in release 0.20.

If you would like the old way of passing in url params you should use version 0.18 backwards.

Every code here is based in axios documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM