获取数据时出错:FetchError:无效的 json 响应正文

问题描述 投票:0回答:1

我是 NodeJS 的新手。我正在尝试使用此代码从该在线 API 获取 json 响应

// server.js
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');

const app = express();
const port = process.env.PORT || 3001;

app.use(cors());

app.get('/api/data', async (req, res) => {
  try {
    const apiUrl = "https://www.swiggy.com/dapi/restaurants/list/v5?lat=28.6083697&lng=77.293112&page_type=DESKTOP_WEB_LISTING"; // Replace with the actual API URL
    const response = await fetch(apiUrl);
    const data = await response.json();
    return res.json(data);
  } catch (error) {
    console.error('Error fetching data:', error);
    return res.status(500).json({ error: 'Internal Server Error' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

当我尝试执行获取请求时,我在控制台中收到此错误

Server is running on port 3001
Error fetching data: FetchError: invalid json response body at https://www.swiggy.com/dapi/restaurants/list/v5?lat=28.6083697&lng=77.293112&page_type=DESKTOP_WEB_LISTING reason: Unexpected token '<', "<html lang"... is not valid JSON
    at /home/priya/Documents/server/node_modules/node-fetch/lib/index.js:273:32
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async /home/priya/Documents/server/index.js:15:18 {
  type: 'invalid-json'
}

我尝试控制台记录我收到的响应

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _events: [Object],
      _readableState: [ReadableState],
      _writableState: [WritableState],
      allowHalfOpen: true,
      _maxListeners: undefined,
      _eventsCount: 5,
      [Symbol(shapeMode)]: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://www.swiggy.com/dapi/restaurants/list/v5?lat=28.6083697&lng=77.293112&page_type=DESKTOP_WEB_LISTING',
    status: 403,
    statusText: 'Forbidden',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

我查找了多个 stackoverflow 答案,但无法找出这里的问题。请帮忙

node.js express server postman fetch
1个回答
0
投票

您收到状态:403,这意味着该请求被禁止。我已经设法在单独的环境中运行它。 如果您使用 axios,那么作为响应,您可以检查该服务器的 html 响应中的数据,我在下面添加了屏幕截图。

© www.soinside.com 2019 - 2024. All rights reserved.