gpt4 book ai didi

javascript - 在 React 应用程序中访问 api 时出错

转载 作者:行者123 更新时间:2023-12-03 02:20:43 33 4
gpt4 key购买 nike

这是我在浏览器中访问 API 时遇到的错误。错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

这是我的 app.js 文件。我基本上尝试使用随机报价生成器 API。这是代码。

import React, { Component } from 'react';

import './App.css';
const PATH_BASE='https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';
class App extends Component {

getquotes=()=>{
fetch(`${PATH_BASE}`)
.then((resp)=>resp.json())
.then(function(data){
console.log(data);
})
.catch(() => console.log("Can’t access " + PATH_BASE + " response. Blocked by browser?"))


}
componentDidMount=()=>{
this.getquotes()
}
render() {
return (
<div className="App">
<h1>Random Quote </h1>
</div>
);
}
}

export default App;

最佳答案

正如 epascarello 所说,托管资源的服务器需要启用 CORS。您可以在客户端执行的操作(可能是您正在考虑的)是将获取模式设置为 CORS(尽管这是我认为的默认设置):

    fetch(request, {mode: 'cors'});

但是,这仍然需要服务器启用 CORS,并允许您的域请求资源。

查看 CORS 文档,以及这段精彩的 Udacity 视频,解释同源政策。

您还可以在客户端使用 no-cors 模式,但这只会给您一个不透明的响应

import React, { Component } from 'react';

import './App.css';
const PATH_BASE='https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';
class App extends Component {

getquotes=()=>{
fetch(`${PATH_BASE}`,{mode: 'no-cors'})
.then((resp)=>resp.json())
.then(function(data){
console.log(data);
})
.catch(() => console.log("Can’t access " + PATH_BASE + " response. Blocked by browser?"))


}
componentDidMount=()=>{
this.getquotes()
}
render() {
return (
<div className="App">
<h1>Random Quote </h1>
</div>
);
}
}

export default App;

关于javascript - 在 React 应用程序中访问 api 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49172098/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com