我在 glitch.me 上创建了一个服务器,我正在尝试从服务器提供数据,但出现以下错误。 localhost/:1 访问 ' https://clem-quote-server.glitch.me/quotes 获取'来自原点'http://localhost:3000 ' 已被 CORS 策略阻止:
No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
不太确定如何解决这个问题
import React, {Component} from "react"
class quotes extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
quotes: quotes
};
}
componentDidMount() {
fetch("https://clem-quote-server.glitch.me/quotes")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
quotes: result.quotes
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, quotes } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{quotes.map(quote => {
return quote;
}
)}
</ul>
);
}
}
}
export default quotes;
我希望能够在每次加载页面时显示数组列表中的一个对象
最佳答案
它失败是因为 CORS,当服务器和客户端处理不同的域时必须包含 CORS。
CORS 包含在 header 中。
以下是在 React 应用程序中启用 corse 的方法:
https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development
CORS 信息:
关于node.js - 向 glitch.me 服务器发出跨域请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56135462/