Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

huangapple go评论63阅读模式
英文:

Azure Databricks rest api blocked by cors policy while making request through ReactJs web app

问题

以下是代码部分的翻译:

import React, { useState } from "react";

function App() {
  const [response, setResponse] = useState("");

  const handleClick = async () => {
    const url = "https:XXXXXXX";
    const jobId = "XXXXXXX";
    const token = "XXXXXXX";

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        job_id: jobId
      }),
    });

    const result = await response.json();
    setResponse(result);
  };

  return (
    <div>
      <button onClick={handleClick}>Run Job</button>
      {response && <p>{response}</p>}
    </div>
  );
}

export default App;

请注意,代码部分已经被翻译成中文。

英文:

Hi am trying to create the trigger button to my react web app. I am getting issue to handle cors policy.
I tried though the postman and It worked fine but i am having issue with reactjs. Also, I don't have any server as a proxy like nodejs to handle.
Is there any way we can handle cors within reactJs ?

import React, { useState } from &quot;react&quot;;

function App() {
  const [response, setResponse] = useState(&quot;&quot;);

  const handleClick = async () =&gt; {
    const url = &quot;https:XXXXXXX&quot;;
    const jobId = &quot;XXXXXXX&quot;
    const token = &quot;XXXXXXX&quot;;

    const response = await fetch(url, {
      method: &quot;POST&quot;,
      headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        job_id:jobId
      ),
    });

    const result = await response.json();
    setResponse(result);
  };

  return (
    &lt;div&gt;
      &lt;button onClick={handleClick}&gt;Run Job&lt;/button&gt;
      {response &amp;&amp; &lt;p&gt;{response}&lt;/p&gt;}
    &lt;/div&gt;
  );
}

export default App;

答案1

得分: 1

我在我的环境中重现了你的代码,即使在发送POST请求以运行Databricks作业时,我也遇到了相同的错误。

我在Spark配置中添加了以下配置,即使如此也没有起作用。
Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

所以,我可以为你提供另一种方法来完成这个任务,即创建一个后端服务器,该服务器提供带有作业ID作为参数的GET请求,端点为'/runjob'。然后,它会向Databricks发送POST请求来触发作业,端点为jobs/run-now/

以下是步骤:

首先,将以下代码添加到你的react-app中。

import React, { useState } from "react";

function App() {
    const [runId, setResponse] = useState("");
    const handleClick = async () => {
        const jobId = "679312719500343";
        const url = "http://localhost:5000/runjob?id=" + jobId;
        const response = await fetch(url, {
            method: "GET",
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Headers": "Content-Type",
            }
        });
        const result = await response.json();
        setResponse(result.run_id);
    };
    return (
        <div style={{ paddingLeft: "500px" }}>
            <button onClick={handleClick}>Run Job</button>
            <p>runId == {runId}</p>
        </div>
    );
}
export default App;

接下来,创建后端服务器。
安装express、axios和cors库。

npm install express cors axios

然后,在新文件backend.js中添加以下代码,然后运行以下命令启动服务器。

node backend.js
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();

app.use(cors({
    origin: '*'
}));

const port = 5000;
const token = "your token";
const baseUrl = "xxxxx/api/2.0/";

app.get('/runjob', async function (req, res) {
    try {
        idx = req.url.match("=")['index'] + 1;
        const jobId = req.url.substring(idx);
        console.log(jobId);
        const headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        };
        const requestBody = {
            job_id: jobId
        };
        const response = await axios.post(`${baseUrl}jobs/run-now/`, requestBody, { headers });
        res.send(response.data);
    } catch (error) {
        res.status(500).send(`Error running job: ${error}`);
    }
});

在服务器启动后,转到reactapp并单击Run Job按钮以获取以下结果。

Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

这是在集群中触发的作业。
Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

你可以看到相似的运行ID。

英文:

I reproduced your code in my environment even .I got the same error when sent the post request , to run the job in databricks.

I added below configurations in spark config, even that did not work.
Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

So, I can give you the alternative way to get this done is by creating a backend server which provide GET request with job id as the parameter at the endpoint &#39;/runjob&#39;
Then it sends POST request to databricks to trigger the job at the endpoint
jobs/run-now/.

Below are the steps,

First,
Add below code into your react-app.

import  React, { useState } from  &quot;react&quot;;

function  App() {
    const [runId, setResponse] =
    useState(&quot;&quot;);
    const  handleClick = async () =&gt; {
    const  jobId = &quot;679312719500343&quot;
    const  url =&quot;http://localhost:5000/runjob?id=&quot;+jobId;
    const  response = await  fetch(url, {
					    method:  &quot;GET&quot;,
		    headers: {
	    &quot;Access-Control-Allow-Origin&quot;:  &quot;*&quot;,
	    &quot;Access-Control-Allow-Headers&quot;:  &quot;Content-Type&quot;,
	    }
	});
const  result = await  response.json();
    setResponse(result.run_id);
    };
return (
&lt;div  style={{paddingLeft:&quot;500px&quot;}}&gt;
&lt;button  onClick={handleClick}&gt;Run Job&lt;/button&gt;
{&lt;p&gt;runId =={runId}&lt;/p&gt;}
&lt;/div&gt;
);
}
export  default  App;

Next, create backed server.
Install the libraries express,axios and cors.

npm install express cors axios

Then add below code in the new file backend.js and
run following command to start the server.

node backend.js


const  express = require(&#39;express&#39;);
const  axios = require(&#39;axios&#39;);
const  cors = require(&#39;cors&#39;);
const  app = express();

app.use(cors({
origin:&#39;*&#39;
}));

const  port = 5000;
const token = &quot;your token&quot;
const  baseUrl = &quot;xxxxx/api/2.0/&quot;

app.get(&#39;/runjob&#39;, async  function(req, res) {
try {
    idx = req.url.match(&quot;=&quot;)[&#39;index&#39;] + 1
    const  jobId = req.url.substring(idx)
    console.log(jobId)
    const  headers = {
    &#39;Authorization&#39;:  `Bearer ${token}`,
    &#39;Content-Type&#39;:  &#39;application/json&#39;
    };
const  requestBody = {
    job_id:  jobId,
};
const  response = await  axios.post(`${baseUrl}jobs/run-now/`, requestBody, { headers });
res.send(response.data);
} catch (error) {
res.status(500).send(`Error running job: ${error}`);
}
});

After the server started go to reactapp and click the Run Job button to get the result as below.

Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

Here is the job triggered in cluster.
Azure Databricks REST API在通过ReactJs web应用程序进行请求时受到CORS策略的阻止。

You can see run id's similar.

huangapple
  • 本文由 发表于 2023年4月7日 01:53:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定