英文:
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 "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;
答案1
得分: 1
我在我的环境中重现了你的代码,即使在发送POST请求以运行Databricks作业时,我也遇到了相同的错误。
所以,我可以为你提供另一种方法来完成这个任务,即创建一个后端服务器,该服务器提供带有作业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
按钮以获取以下结果。
你可以看到相似的运行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.
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 '/runjob'
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 "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;
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('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}`);
}
});
After the server started go to reactapp and click the Run Job
button to get the result as below.
Here is the job triggered in cluster.
You can see run id's similar.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论