简体   繁体   English

如何使用 API 令牌从 REST API 获取数据

[英]How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests.我正在尝试在我的 React 应用程序中使用 Axios 库为 Z80791B8AE76D9 请求从 Jira Rest API 获取数据。 An API token is necessary, in order to access data via the Jira API.为了通过 Jira API 访问数据,需要 API 令牌。 I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.我在我的 Jira 帐户设置中生成了一个 API 令牌,但我不知道如何将它包含在我的 http 请求中以获得访问权限。

This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:这是 Jira 文档提供的用于从 Jira 板获取问题的端点:

curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool

This is the React state hook for setting the data to the fetched data:这是用于将数据设置为获取的数据的 React state 钩子:

    const [jiraTicket, setJiraTicket] = useState([]);

This is the fetch function for the API request (${} will be filled with user input):这是 API 请求的获取 function 请求(${} 将填充用户输入):

    function getJiraTicket() {
    axios.get(`${username}:${apiToken}@Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
        .then((res) => {
            const data = res.data;
            setJiraTicket(data);
        })
}

The button inside the react component return should invoke the fetch function: react 组件返回中的按钮应该调用 fetch function:

return(
   <Container>
      <Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
   </Container>
);

This is the error I'm currently getting, because the authorization is not working the way I did it (I replaced the provided username, API token etc. for this example):这是我目前遇到的错误,因为授权没有按照我的方式工作(我替换了提供的用户名、API 令牌等,用于此示例):

GET http://localhost:3000/username:apitoken@https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found) GET http://localhost:3000/username:apitoken@https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404(未找到)

Edit:编辑:

My current approach:我目前的做法:

    function getJiraTicket() {
    axios.get(`${userName}:${apiToken}@https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
        auth: {
            username: userName,
            password: apiToken,
        },
        withCredentials: true
    })
        .then((res) => {
            const data = res.data;
            console.log(data);
            setJiraTicket(data);
        })
        .catch(err => {
            // This error means: The request was made and the server responded with a status code
            if(err.res) {
                console.log(err.res.data);
                console.log(err.res.status);
                console.log(err.res.headers);
                console.log("request was made and server responded with status");
            // The request was made but no response was received
            } else if (err.request) {
                console.log(err.request);
                console.log("request was made, but no response was received");
            // Something happened in setting up the request that triggered an error
            } else {
                console.log("Error", err.message);
                console.log("request is note set up correctly");
            }
            console.log(err.config);
        })

Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"当前错误,我根据 axios 文档定义:“请求已发出,但未收到响应”

Endpoint that works well in Postman (Basic auth is provided in Postman): https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid在 Postman 中运行良好的端点(Postman 中提供了基本身份验证): https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid

Axios uses a headers config for get/post so you should not include them in your URL. Axios 使用标题配置来获取/发布,因此您不应将它们包含在 URL 中。 Here is a general example of how you should construct the URL and apply headers:以下是您应该如何构造 URL 并应用标头的一般示例:

let axiosUrl = `${username}:${apiToken}@https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
    baseURL: axiosUrl,
    method: 'get',
    headers: {
        "Content-Type": "application/json"
    },
    //timeout: 2000,
})
    .then((res) => {
        setJiraTicket(res.data);
    })
     .catch(function (error) {
         console.log(error);
     });

Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly.更新:当应用程序尝试直接访问 Jira API 端点时,不允许 CORS 访问。 This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication.进行此限制是为了防止对特定 Jira 站点的随机身份验证请求,因为访问是基于 session 的身份验证。 However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:但是,如果使用 OAuth 2.0 而不是基本身份验证,则可以访问 API 端点,因为应用程序将通过此链接将用户重定向到 Jira 身份验证本身:

https://auth.atlassian.com/authorize ? https://auth.atlassian.com/authorize ? audience=api.atlassian.com&观众=api.atlassian.com&
client_id=YOUR_CLIENT_ID& client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&范围=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL& redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent

Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues来源: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM