【问题标题】:I wonder why there are different results from errors when I use express, axios, and cors我想知道为什么我使用express,axios和cors时会出现不同的错误结果
【发布时间】:2021-09-17 13:34:30
【问题描述】:

当我爬到我的大学网站的一部分时,出现错误。

Failed to load resource: net::ERR_CONNECTION_REFUSED (localhost:3000/:1)
createError.js:16 Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:99)

我尝试了其他方法,但我不确定为什么它会显示“加载...”并且在控制台中出现错误。

该网站正在运行,但无法正常抓取并显示“加载...”

这是 kangnam.js :

const axios = require('axios');
const cheerio = require('cheerio');
const log = console.log;
const express = require("express");
const cors = require("cors");
const PORT = 4000;
const app = express();

app.use(cors());

const getHTML = async () => {
    try {
        return await axios.get('https://web.kangnam.ac.kr', {
            headers: {
                Accept: 'text/html'
            }
        });
    } catch (error) {
        console.log(error);
    }
};

app.get("/", (req, res) => {
    getHTML()
        .then(html => {
        const $ = cheerio.load(html.data);
        const $allNotices = $("ul.tab_listl div.list_txt");

        let resultArr = [];
        $allNotices.each(function(idx, element) {
            let itemObj = {
                title : $(this).children('a').attr('title'),
                url : $(this).children('a').attr('href'),
            };
            resultArr.push(itemObj);
        });
        
        resultArr.forEach((element) => {
            console.log(`현재 ${element._title}의 현황 : ${element._url}`);
        });
        return resultArr;

        // const data = ulList.filter(n => n.title);
        // return data;
    }). then((data) => res.send(data));
});

app.listen(PORT, () => 
    console.log(`Example app listening at http://localhost:${PORT}`)
);

这是 NoticesList.js :

import React, {useEffect, useState} from 'react';
import styled from 'styled-components';
import NoticesItem from './NoticesItem';
import axios from "axios";

const NoticesListBlock = styled.div`
    box-sizing: border-box;
    padding-bottom: 3rem;
    width: 768px;
    margin: 0 auto;
    margin-top: 2rem;
`;

const sampleArticle = {
    title: 'title',
    url: 'https://google.com',
};

const NoticesList = () => {
    
    const [data, setData] = useState(null);
    useEffect(() => {
        const getData = async() => {
            const datas = await axios.get("http://localhost:3000/");
            setData(datas.data);
        };
        getData();
    }, []);
    
    useEffect(() => {
        console.log(data);
    }, [data]);
    
    if(data === null){
        return <div>Load....</div>;
    }else{
        console.log(data);
        return (
            <div>
                {data.map((ele) => (
                    <>
                        <div>
                            {ele.title};
                        </div>
                    <br/>
                    </>
                ))}
            </div>  
        );
    };

    
    
};

export default NoticesList;

这是 NoticesItem.js :

import React from 'react';
import styled from 'styled-components';

const NoticesItemBlock = styled.div`
    display: flex;
    .contents {
        h6 {
            margin: 15px;
            a {
                color: black;
            }
        }
    }
    & + & {
        margin-top: 1.5rem;
    }
`;

const NoticesItem = ({ article }) => {
    const { title, url } = article;
    return (
        <NoticesItemBlock>
            <div className="contents">
                <h6>
                    <a href={url} target="_blank" rel="noopener noreferrer">
                        {title}
                    </a>
                </h6>
            </div>
        </NoticesItemBlock>
    );
};

export default NoticesItem;

【问题讨论】:

  • 看起来您正在端口 4000 上启动本地服务器,但获取的是 localhost:3000
  • @ibsn 我将const datas = await axios.get("http://localhost:3000/"); 编辑为const datas = await axios.get("http://localhost:4000/"); 但错误是一样的......错误是:GET http://localhost:4000/ net::ERR_CONNECTION_REFUSED Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:99)
  • 会不会是因为您试图从 HTTPS 页面访问 HTTP 资源?
  • @Sterex 那我该怎么办?
  • @Sterex 你能远程修改我的代码吗?

标签: node.js reactjs web-crawler


【解决方案1】:

尝试在 goormide 上部署 API,只需将 kangnam.js 的最后一部分更改为:

app.listen(3000, function() { 
  console.log('Server listening on port 3000'); 
});

这将提供如下链接:https://server-clgoz.run-eu-central1.goorm.io/ 您将使用它来代替:http://localhost:4000/ 在 NoticesList.js 上

您还可以在此文件中设置如下变量:

const site="https://web.kangnam.ac.kr/";

然后在map函数中:

<a href={site+decodeURIComponent(ele.url.slice(17))}>{ele.title}</a>

这将提供指向该网站的链接。

祝你好运:) !!!

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    相关资源
    最近更新 更多