Javascript 是否返回的值不正确?
我在SpringBoot中设置了api,当您调用其中一个方法时,它将返回一个成功或失败的字符串。然而,我的获取控制台显示成功,但当我尝试将其保存到变量时,它会显示未定义。如何从api中获取成功或失败字符串Javascript 是否返回的值不正确?,javascript,reactjs,api,fetch,Javascript,Reactjs,Api,Fetch,我在SpringBoot中设置了api,当您调用其中一个方法时,它将返回一个成功或失败的字符串。然而,我的获取控制台显示成功,但当我尝试将其保存到变量时,它会显示未定义。如何从api中获取成功或失败字符串 handleSubmit(event) { var a ; event.preventDefault(); this.setState({username:'poop'}) console.log("submit"); fetch('http://localhost:808
handleSubmit(event) {
var a ;
event.preventDefault();
this.setState({username:'poop'})
console.log("submit");
fetch('http://localhost:8080/login/'+this.state.username+'/'+this.state.password,{
method: 'GET',
}).then((resp)=> resp.text())
.then(function(data){
a= data;
})
我希望您以json的形式发送响应。如果是,请使用。然后((resp)=>resp.json())。请检查下面使用fetch调用api的完整示例
import React, {Component} from "react";
class FetchExample extends React.Component {
state = {
isLoading: false,
questions: [],
error: null
};
async fetchQuestions(){
fetch(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`,)
.then(response => {
if (response.status !== 200) {
console.log('There was a problem. Status Code: ' + response.status);
return;
}
response.json().then(data => {
console.log(data);
this.setState({
questions: data,
isLoading: false
})
});
}
)
.catch(function (error) {
console.log('Error: ', error);
this.setState({error, isLoading: false})
});
};
render() {
const {isLoading, questions, error} = this.state;
return (
<React.Fragment>
<h1>Random Question</h1>
<button onClick={this.fetchQuestions}>Click for calling API using fetch</button>
{error ? <p>{error.message}</p> : null}
{!isLoading && questions.results ? (
questions.results.map((questions, index) => { //something right here
//is erroring
const {question, category, type, difficulty} = questions;
return (
<div key={index}>
<p>Question: {question}</p>
<p>Question Type: {type}</p>
<p>Difficulty: {difficulty}</p>
<hr/>
</div>
);
})
) : isLoading ? (
<h3>Loading...</h3>
) : null}
</React.Fragment>
);
}
}
export default FetchExample;
import React,{Component}来自“React”;
类FetchExample扩展了React.Component{
状态={
孤岛加载:false,
问题:[],
错误:null
};
异步获取问题(){
取回(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`,)
。然后(响应=>{
如果(response.status!==200){
console.log('出现问题,状态代码:'+响应.Status);
返回;
}
response.json().then(数据=>{
控制台日志(数据);
这是我的国家({
问题:数据,
孤岛加载:false
})
});
}
)
.catch(函数(错误){
console.log('Error:',Error);
this.setState({error,isLoading:false})
});
};
render(){
const{isLoading,questions,error}=this.state;
返回(
随机问题
单击此处可使用fetch调用API
{error?{error.message}:null}
{!isLoading&&questions.results(
questions.results.map((questions,index)=>{//这里有一些东西
//这是一个错误
常量{问题,类别,类型,难度}=问题;
返回(
问题:{问题}
问题类型:{Type}
难度:{难度}
);
})
):正在加载(
加载。。。
):null}
);
}
}
导出默认抓取示例;
我发送了一个单字字符串作为响应。例如,如果以文本或字符串作为响应,“失败”,请使用response.text()。然后(数据=>{console.log(text);})代码>