[英]React - CORS issue No 'Access-Control-Allow-Origin' header is present on the requested resource
I am building a React app to scrape content from a site through server and get that data and display it on the client side.我正在构建一个 React 应用程序,通过服务器从站点抓取内容并获取该数据并将其显示在客户端。
I am web-scraping content from a site in server.js.我正在从 server.js 中的网站抓取内容。
I am trying to get that data through axios call in app.js in the client side.我正在尝试通过客户端 app.js 中的 axios 调用获取该数据。
However, I am getting this CORS error, "No 'Access-Control-Allow-Origin' header is present on the requested resource".但是,我收到此 CORS 错误,“请求的资源上不存在‘Access-Control-Allow-Origin’标头”。
Could you please help me fix this issue?你能帮我解决这个问题吗?
Here is my server.js :这是我的 server.js :
var request = require('request'); var cheerio = require('cheerio'); var express = require('express'); var app = express(); app.get('/news/:newsName', function(req, res) { var data = ""; const techCrunchURL = "https://techcrunch.com/2018/05/04/nsa-triples-metadata-collection-numbers-sucking-up-over-500-million-call-records-in-2017/"; var techCrunchNewsItems = { bodyOne: '', bodyTwo: '' }; switch(req.params.newsName) { case 'tech-crunch': request(techCrunchURL, function(err, response, html) { var $ = cheerio.load(html); if($('.article-content').children('p').eq(0).text().split(' ').length > 50) { techCrunchNewsItems.bodyOne = $('.article-content').children('p').eq(0).text(); } else { techCrunchNewsItems.bodyOne = $('.article-content').children('p').eq(0).text(); techCrunchNewsItems.bodyTwo = $('.article-content').children('p').eq(1).text(); } data = techCrunchNewsItems; res.send(JSON.stringify(data)); }); break; default: data = 'Please type in correct news source'; break; } }); var server = app.listen(8082, function () { var host = server.address().address; var port = server.address().port; console.log("Example app listening at http://%s:%s", host, port); });
Here is my app.js :这是我的 app.js :
import React, { Component } from 'react'; import { render } from 'react-dom'; import axios from 'axios'; import '../css/style.css'; export default class Hello extends Component { constructor() { super(); this.techCrunchNewsDate = ''; } componentDidMount() { axios.get(`http://localhost:8082/news/tech-crunch`) .then(res => { const data = res.data; this.techCrunchNewsDate = data; }); } render() { console.log(this.techCrunchNewsDate); return ( <div> Hello from react </div> ); } } render(<Hello />, document.getElementById('app'));
您可以尝试在res.send()
之前添加res.set('Access-Control-Allow-Origin', '*')
res.send()
This is not a React issue, it's a general issue with any JS-based app.这不是 React 问题,而是任何基于 JS 的应用程序的普遍问题。 The resource you are attempting to scrape is what is causing this, not your code.
您尝试抓取的资源是导致此问题的原因,而不是您的代码。
If you haven't already read it, read this: MDN CORS Article如果你还没有读过,请阅读: MDN CORS 文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.