Python 从API获取内容
我的前端(ReactJS)位于Python 从API获取内容,python,reactjs,response,Python,Reactjs,Response,我的前端(ReactJS)位于localhost:3000,它向我的后端发送请求(localhost:5090/api/fetch/) 前端代码段: handleSubmit(event) { //alert('A name was submitted: ' + this.state.value); fetch('http://127.0.0.1:5090/api/fetch/' + this.state.value, {
localhost:3000
,它向我的后端发送请求(localhost:5090/api/fetch/
)
前端代码段:
handleSubmit(event) {
//alert('A name was submitted: ' + this.state.value);
fetch('http://127.0.0.1:5090/api/fetch/' + this.state.value,
{
mode: 'no-cors'
}).then((response) => console.log(response));
event.preventDefault();
}
后端接收请求:
127.0.0.1 - - [22/Oct/2020 10:54:44] "GET /api/fetch/212 HTTP/1.1" 200 -
和带有{stock:name}
蟒蛇
def get(self, name):
print(name)
return {"stock": name}
然而,我无法得到回应
我遗漏了什么,我可以实际看到{“stock”:}
的响应数据?你能这样试试吗
.then(response => response.json())
.then(result => {
console.log(result);
})
})
.catch(error => {
console.log('Error ' + error);
})
Ejaz答案中的代码应该可以正常工作,但我建议您阅读FetchAPI的官方文档 您不能只记录来自fetch api的响应,它只返回一个承诺, 您不能打印response.body,因为它返回一个可读的流,请使用body上的接口方法将流读入完成 根据api返回的数据类型,可以调用response.text()或response.json() 使用FetchAPI,您必须处理承诺,我将尝试使用async/await重构handleSubmit函数,这是一种更干净的处理承诺的方法
async handleSubmit(event) {
event.preventDefault();
try{
let response = await fetch('http://127.0.0.1:5090/api/fetch/'+this.state.value, {
mode: 'no-cors'});
console.log(await response.json());
}
catch(error => console.log('Error ' + error));
}
发送不带cors的请求将返回不透明类型的对象 更新我的后端以允许所有源 来自前端JavaScript的跨源请求的情况是,默认情况下,浏览器会阻止前端代码访问跨源的资源。如果Access Control Allow Origin在响应中,那么浏览器将放松该阻塞,并允许您的代码访问响应 然后删除前端中的模式至
cors
fetch('http://127.0.0.1:5090/api/fetch/' + this.state.value,
{
}).then(response => response.json())
.then(response => {
console.log(response)
})
.catch(error => {
console.log('Error ' + error);
})
成功显示数据
(答复)
错误语法错误:输入意外结束
当前实际代码:fetch('http://127.0.0.1:5090/api/fetch/“+this.state.value,{mode:'no cors'})。然后(response=>response.json())。然后((result)=>{console.log(result);})。catch(error=>{console.log('error'+error);})
,但仍然需要使用response.json()并处理它返回的承诺,以便能够打印响应
fetch('http://127.0.0.1:5090/api/fetch/' + this.state.value,
{
}).then(response => response.json())
.then(response => {
console.log(response)
})
.catch(error => {
console.log('Error ' + error);
})
{stock: "111"}