postman 获取数据时出错:FetchError:无效的json响应体

zdwk9cvp  于 11个月前  发布在  Postman
关注(0)|答案(1)|浏览(127)

我是一个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的答案,但无法找出问题在这里。请帮助

6tqwzwtp

6tqwzwtp1#

您正在获取状态:403,这意味着请求被禁止.我已经设法运行这是在一个单独的环境.如果你使用axios然后在响应中,你可以检查该服务器的html响应中的数据我在下面添加一个截图.

相关问题