By Guest

Unnamed Paste

Javascript 2.56 KiB 49 one month ago
const cheerio = require('cheerio'); const express = require('express') const app = express() require('dotenv').config() const apiKey = process.env.API_KEY const router = express.Router(); app.get('/api/upcoming', async (req, res) => { try { const getUpcoming = async () => { try { const siteUrl = `https://spacelaunchnow.me/launch/upcoming/spacex` const req = await fetch(siteUrl) const data = await req.text() const $ = cheerio.load(data) let dataArr = [] $('div.card.text-left').each((index, element) => { let launchName = $(element).find('h4.card-title').text() let base = $(element).find('div.col-md-8.text-md-left.text-center').text().split("<br>")[0].split("\n") let spaceAgencyName = `${base[2]} ${base[3]}` let launchSite = base[4] let launchDate = base[5] let rocketImage = $(element).find('div.col-md-4.text-center > img').attr('src') dataArr.push({ launchName, spaceAgencyName, launchSite, launchDate, rocketImage, }) }) $('div.card-body.mx-5').each((index, element) => { let status = $(element).find('h5').text().replace('Status: ', '').split('Mission')[0].replace('Unknown', '') let mission = $(element).find('p.card-text').text() let linkID = $(element).find('a').attr('href').replace('/launch/', '') dataArr.push({ status, mission, linkID, }) }) return dataArr } catch (error) { console.error(error) } } const apiData = await getUpcoming() return res.status(200).json({ result: apiData, }) } catch (error) { return res.status(500).json({ error: error.toString(), }) } }) app.listen(process.env.PORT, () => { console.log(`App listening on port ${process.env.PORT}`) })