【发布时间】:2021-06-11 03:38:46
【问题描述】:
我已经为酒吧建立了一个无服务器响应网站,并通过获取请求检索啤酒列表(作为 XML):
componentDidMount() {
const url = 'http://****************/taplist.xml'
const proxyURL = 'https://cors-anywhere.herokuapp.com/'
this.setState({
isLoading: true
})
fetch(proxyURL + url)
.then(res => res.text())
.then(beerXML => {
let beerJs = new XMLParser().parseFromString(beerXML)
this.setState({
isLoading:false,
beers: beerJs
})
})
}
这工作正常,但最近 API 失败了。没有返回数据,我在浏览器中收到以下错误:
Home.jsx:27 GET https://cors-anywhere.herokuapp.com/http://************/taplist.xml 403 (Forbidden)
bundle.js:1 Uncaught (in promise) TypeError: Cannot read property 'value' of undefined
at bundle.js:1
at Array.map (<anonymous>)
at e.value (bundle.js:1)
at e.value (bundle.js:1)
at Home.jsx:30
我怀疑“任何地方的 Cors”代理失败,因此没有返回任何数据。我将变量 beerXML 记录到了应该显示啤酒数据的控制台,但没有产生任何结果。
谁能建议对我当前的 API 调用进行调整,或者建议使用新的代理?或者任何其他可以解决这个问题的方法?
这是负责获取和呈现数据的整个组件:
import React from 'react'
import './styles.css'
import hashi_logo_2 from './Photos/hashi_logo_2.png'
import TileList from './TileList'
import OnNextList from './OnNextList'
import Nav from './Nav'
import twitter_logo from './Photos/twitter_logo.png'
import facebook_logo from './Photos/facebook_logo.png'
const XMLParser = require('react-xml-parser')
class Home extends React.Component {
constructor() {
super()
this.state = {
beers:[],
isLoading:false
}
}
componentDidMount() {
const url = 'http://******************/taplist.xml'
const proxyURL = 'https://cors-anywhere.herokuapp.com/'
this.setState({
isLoading: true
})
fetch(proxyURL + url)
.then(res => res.text())
.then(beerXML => {
console.log(`this is beerJs: ${beerXML}`)
let beerJs = new XMLParser().parseFromString(beerXML)
this.setState({
isLoading:false,
beers: beerJs
})
})
}
render() {
return (
<div className = 'home'>
<div className = 'home-nav'>
<Nav/>
</div>
<main>
<div className='main__image'>
<img src= {hashi_logo_2}/>
</div>
</main>
<div>
{this.state.isLoading === false ?
<TileList beerList = {this.state.beers}/>
:
<h1 className = 'loading-h1'>Loading tap beers....</h1>
}
</div>
<div className = 'on-next-section'>
<OnNextList beerList = {this.state.beers}/>
</div>
<footer>
<a href = 'https://twitter.com/*********'>
<img className = 'img-footer' src = {twitter_logo} ></img>
</a>
<a href ='https://www.facebook.com/*******'>
<img className = 'img-footer' src = {facebook_logo} ></img>
</a>
</footer>
</div>
)
}
}
export default Home
谢谢
【问题讨论】:
-
我怀疑问题出在终端服务器上,而不是代理服务器上。因为这是一个 403 禁止错误。
-
如果你去cors-anywhere.herokuapp.com,你会发现你不应该将它用于生产(它是用纯文本编写的)。您要么需要配置 xml 所在的服务器以配置 access-control-allow-origin 并允许您直接获取,要么使用其他代理,甚至自己制作。
-
可以先用邮递员试试,大哥
标签: javascript reactjs cors fetch