首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React.js不能调用API

React.js不能调用API
EN

Stack Overflow用户
提问于 2022-03-12 07:04:00
回答 1查看 760关注 0票数 0

我有一个简单的React.js应用程序。我想测试它是否可以从我的API中调用端点。我的API和React.js应用程序都在使用Keycloak进行身份验证。

下面是我的API端点:

代码语言:javascript
复制
[HttpGet]
[Route("authorization")]
[Authorize(Roles = "prototype-user")]
public string TestAuthorization()
{
    return "Authorization is working!";
}

这将在邮递员中测试时显示Authorization is working消息。所有其他端点在邮递员中都能很好地工作。

现在,我尝试在我的React.js应用程序中调用这个端点,该应用程序也使用Keycloak。这是我的代码片段

代码语言:javascript
复制
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的新手,所以我不知道如何解决这个问题。我已经找过其他的推荐信了,但找不到。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-14 07:11:50

通过将授权头中的token更改为bearer已经解决了这个问题。

代码语言:javascript
复制
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)
        )
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71447634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档