我有一个简单的React.js应用程序。我想测试它是否可以从我的API中调用端点。我的API和React.js应用程序都在使用Keycloak进行身份验证。
下面是我的API端点:
[HttpGet]
[Route("authorization")]
[Authorize(Roles = "prototype-user")]
public string TestAuthorization()
{
return "Authorization is working!";
}这将在邮递员中测试时显示Authorization is working消息。所有其他端点在邮递员中都能很好地工作。
现在,我尝试在我的React.js应用程序中调用这个端点,该应用程序也使用Keycloak。这是我的代码片段
constructor(props) {
super(props);
this.state = {
result: [],
token: null
};
//this is passed from another component derived from keycloak.idToken
this.state.token = this.props.token
}
componentDidMount(){
var url = this.getBaseUrl() + "/authorization";
fetch(url, {
method: "get",
credentials: "include",
headers: {
'Authorization': `token ${this.state.token}`,
},
}).then(
res=>res.json())
.then(
result=>{
this.setState({result:result})
}
).catch(error =>
alert(error)
)
}这将返回一个错误:SyntaxError:JSON.parse: unexpected character at line 1 column 1 of JSON data,甚至不输入我的API断点。
有人能告诉我这是怎么回事吗?我是React.js的新手,所以我不知道如何解决这个问题。我已经找过其他的推荐信了,但找不到。
谢谢!
发布于 2022-03-14 07:11:50
通过将授权头中的token更改为bearer已经解决了这个问题。
componentDidMount() {
var url = this.getBaseUrl() + "/authorization";
fetch(url, {
method: "get",
credentials: "include",
headers: {
'Authorization': `Bearer ${this.state.token}`,
},
}).then((response) => {
if (response.status == 200) {
return response.json()
} else {
throw new Error(response.status)
}
})
.then(result => {
this.setState({ result: result })
}).catch(error =>
alert(error)
)
}https://stackoverflow.com/questions/71447634
复制相似问题