简体   繁体   中英

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.

I am web-scraping content from a site in server.js.

I am trying to get that data through axios call in app.js in the client side.

However, I am getting this CORS error, "No 'Access-Control-Allow-Origin' header is present on the requested resource".

Could you please help me fix this issue?

Here is my 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 :

 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM