javascript Axios返回html数据而不是json

abithluo  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(324)

在Nextjs的getInitialProps函数中,我尝试从Kubernetes容器内运行的后端获得响应。

import axios from 'axios';

const buildClient = ({ req }) => {

  if (typeof window === 'undefined') {
    // we are on the server
    console.log('getting executed in the server')
    const instance = axios.create({
      baseURL: 'http://ingress-nginx-controller.ingress-nginx.svc.cluster.local',
      headers: {
        ...req.headers,
        accept: 'application/json',
        'Content-Type': 'application/json'
      },
    });
    instance.defaults.headers.get['content-type'] = 'application/json';
    return instance;
  } else {
    //  we must be on the browser
    console.log('getting executed in the browser')
    return axios.create({
      baseURL: '/'
    })
  }

};

export default buildClient;

这就是我创建axios示例的方式

const client = buildClient(ctx);
console.log(client.defaults.headers);

给予

{
[client]   common: { Accept: 'application/json, text/plain, */*' },
[client]   delete: {},
[client]   get: { 'content-type': 'application/json' },
[client]   head: {},
[client]   post: { 'Content-Type': undefined },
[client]   put: { 'Content-Type': undefined },
[client]   patch: { 'Content-Type': undefined },
[client]   host: 'ticketing.dev',
[client]   'x-request-id': 'e38199c89b2b2584aac5480aed9a745b',
[client]   'x-real-ip': '192.168.49.1',
[client]   'x-forwarded-for': '192.168.49.1',
[client]   'x-forwarded-host': 'ticketing.dev',
[client]   'x-forwarded-port': '443',
[client]   'x-forwarded-proto': 'https',
[client]   'x-forwarded-scheme': 'https',
[client]   'x-scheme': 'https',
[client]   'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
[client]   'sec-ch-ua-mobile': '?0',
[client]   'sec-ch-ua-platform': '"Linux"',
[client]   'upgrade-insecure-requests': '1',
[client]   'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
[client]   accept: 'application/json',
[client]   'sec-fetch-site': 'none',
[client]   'sec-fetch-mode': 'navigate',
[client]   'sec-fetch-user': '?1',
[client]   'sec-fetch-dest': 'document',
[client]   'accept-encoding': 'gzip, deflate, br',
[client]   'accept-language': 'en-IN,en;q=0.9',
[client]   'Content-Type': 'application/json'
[client] }

现在

const res = await client.get('/api/tickets');
console.log(res.headers);

给予

AxiosHeaders {
[client]     server: 'openresty/1.13.6.1',
[client]     date: 'Thu, 09 Feb 2023 18:44:12 GMT',
[client]     'content-type': 'text/html',
[client]     'transfer-encoding': 'chunked',
[client]     connection: 'close'
[client]   },

当我使用console. log(www.example.com)时,它会显示一个巨大的HTML数据块,提示在构建axios示例时,我已经将header设置为header:res.data"应用程序/json"、"内容类型":"application/json "},位于console. log(res)对象内 'application/json', 'Content-Type': 'application/json' }, inside the console.log(res) object

request: <ref *1> ClientRequest {
[client]     _events: [Object: null prototype] {
[client]       abort: [Function (anonymous)],
[client]       aborted: [Function (anonymous)],
[client]       connect: [Function (anonymous)],
[client]       error: [Function (anonymous)],
[client]       socket: [Function (anonymous)],
[client]       timeout: [Function (anonymous)],
[client]       finish: [Function: requestOnFinish]
[client]     },
[client]     _eventsCount: 7,
[client]     _maxListeners: undefined,
[client]     outputData: [],
[client]     outputSize: 0,
[client]     writable: true,
[client]     destroyed: true,
[client]     _last: true,
[client]     chunkedEncoding: false,
[client]     shouldKeepAlive: false,
[client]     maxRequestsOnConnectionReached: false,
[client]     _defaultKeepAlive: true,
[client]     useChunkedEncodingByDefault: false,
[client]     sendDate: false,
[client]     _removedConnection: false,
[client]     _removedContLen: false,
[client]     _removedTE: false,
[client]     strictContentLength: false,
[client]     _contentLength: 0,
[client]     _hasBody: true,
[client]     _trailer: '',
[client]     finished: true,
[client]     _headerSent: true,
[client]     _closed: true,
[client]     socket: Socket {
[client]       connecting: false,
[client]       _hadError: false,
[client]       _parent: null,
[client]       _host: 'ingress-nginx-controller.ingress-nginx.svc.cluster.local',
[client]       _closeAfterHandlingError: false,
[client]       _readableState: [ReadableState],
[client]       _events: [Object: null prototype],
[client]       _eventsCount: 6,
[client]       _maxListeners: undefined,
[client]       _writableState: [WritableState],
[client]       allowHalfOpen: false,
[client]       _sockname: null,
[client]       _pendingData: null,
[client]       _pendingEncoding: '',
[client]       server: null,
[client]       _server: null,
[client]       parser: null,
[client]       _httpMessage: [Circular *1],
[client]       [Symbol(async_id_symbol)]: 109151,
[client]       [Symbol(kHandle)]: null,
[client]       [Symbol(lastWriteQueueSize)]: 0,
[client]       [Symbol(timeout)]: null,
[client]       [Symbol(kBuffer)]: null,
[client]       [Symbol(kBufferCb)]: null,
[client]       [Symbol(kBufferGen)]: null,
[client]       [Symbol(kCapture)]: false,
[client]       [Symbol(kSetNoDelay)]: true,
[client]       [Symbol(kSetKeepAlive)]: true,
[client]       [Symbol(kSetKeepAliveInitialDelay)]: 60,
[client]       [Symbol(kBytesRead)]: 21665,
[client]       [Symbol(kBytesWritten)]: 794
[client]     },
[client]     _header: 'GET /api/tickets HTTP/1.1\r\n' +
[client]       'Accept: application/json\r\n' +
[client]       'content-type: application/json\r\n' +
[client]       'host: ticketing.dev\r\n' +
[client]       'x-request-id: e38199c89b2b2584aac5480aed9a745b\r\n' +
[client]       'x-real-ip: 192.168.49.1\r\n' +
[client]       'x-forwarded-for: 192.168.49.1\r\n' +
[client]       'x-forwarded-host: ticketing.dev\r\n' +
[client]       'x-forwarded-port: 443\r\n' +
[client]       'x-forwarded-proto: https\r\n' +
[client]       'x-forwarded-scheme: https\r\n' +
[client]       'x-scheme: https\r\n' +
[client]       'sec-ch-ua: "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"\r\n' +
[client]       'sec-ch-ua-mobile: ?0\r\n' +
[client]       'sec-ch-ua-platform: "Linux"\r\n' +
[client]       'upgrade-insecure-requests: 1\r\n' +
[client]       'user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36\r\n' +
[client]       'sec-fetch-site: none\r\n' +
[client]       'sec-fetch-mode: navigate\r\n' +
[client]       'sec-fetch-user: ?1\r\n' +
[client]       'sec-fetch-dest: document\r\n' +
[client]       'accept-encoding: gzip, deflate, br\r\n' +
[client]       'accept-language: en-IN,en;q=0.9\r\n' +
[client]       'Connection: close\r\n' +
[client]       '\r\n',
[client]     _keepAliveTimeout: 0,
[client]     _onPendingData: [Function: nop],
[client]     agent: Agent {
[client]       _events: [Object: null prototype],
[client]       _eventsCount: 2,
[client]       _maxListeners: undefined,
[client]       defaultPort: 80,
[client]       protocol: 'http:',
[client]       options: [Object: null prototype],
[client]       requests: [Object: null prototype] {},
[client]       sockets: [Object: null prototype] {},
[client]       freeSockets: [Object: null prototype] {},
[client]       keepAliveMsecs: 1000,
[client]       keepAlive: false,
[client]       maxSockets: Infinity,
[client]       maxFreeSockets: 256,
[client]       scheduling: 'lifo',
[client]       maxTotalSockets: Infinity,
[client]       totalSocketCount: 0,
[client]       [Symbol(kCapture)]: false
[client]     },

除了在axios overriding defaults documentation中提到的之外,我还将"内容类型"重写为"应用程序/json",但在res.头中,内容类型是text/html。
我感到困惑,如果我得到的html响应,由于提供的头或有一些错误的URL端点或api。

qojgxg4l

qojgxg4l1#

Accept头告诉服务器您将接受返回的数据类型。
服务器可以对它执行以下三种操作之一:

  • 使用它为您请求的资源选择最合适的数据格式并将其发送给您
  • 使用406 Not Acceptable状态代码进行响应,告诉您它没有您接受格式的可用资源
  • 完全忽略它

完全忽略它是大多数服务器的默认行为。
如果您想让服务器使用JSON响应(有条件地或无条件地),那么可以配置服务器的任何人都必须配置服务器来执行此操作。

相关问题