簡體   English   中英

React - CORS 問題請求的資源上不存在“Access-Control-Allow-Origin”標頭

[英]React - CORS issue No 'Access-Control-Allow-Origin' header is present on the requested resource

我正在構建一個 React 應用程序,通過服務器從站點抓取內容並獲取該數據並將其顯示在客戶端。

我正在從 server.js 中的網站抓取內容。

我正在嘗試通過客戶端 app.js 中的 axios 調用獲取該數據。

但是,我收到此 CORS 錯誤,“請求的資源上不存在‘Access-Control-Allow-Origin’標頭”。

你能幫我解決這個問題嗎?

這是我的 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); });

這是我的 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()

這不是 React 問題,而是任何基於 JS 的應用程序的普遍問題。 您嘗試抓取的資源是導致此問題的原因,而不是您的代碼。

如果你還沒有讀過,請閱讀: MDN CORS 文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM