我想從 HTML 頁面發送 JSON http POST。此處使用 Fetch API。content-type為“application/x-www-form-urlencoded”或“text/plain”時可以發帖成功,如果content-type為“application/json”則發帖失敗。我已經嘗試過 Fetch 和 Axios API。
這是我的 HTML 客戶端代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<h1 id ="h1">post test</h1>
<input type="submit" value="post" onclick="sendpost()">
<script>
function sendpost()
{
const Url = 'https://my-worker.sgcloud.workers.dev/';
const data = {
name: 'moe',
age: '50'
};
fetch(Url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.text()
.then(text => {
document.getElementById("h1").innerHTML = text;
}))
.catch(err => console.log(err))
}
</script>
</body>
</html>
開發工具的錯誤是:
POST https://my-worker.sgcloud.workers.dev/ net::ERR_FAILED
服務器在我的 cloudflare 作業者中:https://my-worker.sgcloud.workers.dev/,Access-Control-Allow-Origin 已打開。您可以嘗試發布到我的服務器。服務器代碼是:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
if (request.method == 'GET') {
return new Response('Hello Worker!', {
headers: { 'content-type': 'text/plain', 'Access-Control-Allow-Origin': '*' },
});
} else if (request.method == 'POST') {
return new Response('Response for POST!', {
headers: { 'content-type': 'text/plain', 'Access-Control-Allow-Origin': '*' },
});
} else {
response = new Response('Expected POST', { status: 500 });
}
}
因為我可以從在線工具發布 json,所以我的客戶端代碼發送 application/json 應該有問題(客戶端代碼可以發送 text/plain 或 application/x-www-form-urlencoded,已測驗)。我應該如何更改我的代碼以發送 json?謝謝
uj5u.com熱心網友回復:
我想我知道原因。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
對于跨域資源共享 (CORS) 情況:此外,對于可能對服務器資料造成副作用的 HTTP 請求方法(特別是 GET 以外的 HTTP 方法,或具有某些 MIME 型別的 POST),規范要求瀏覽器“ preflight”請求,使用 HTTP OPTIONS 請求方法從服務器請求支持的方法,然后在服務器“批準”后發送實際請求。
有些請求不會觸發 CORS 預檢。這些被稱為簡單請求。Content-Type 標頭中指定的媒體型別允許的唯一型別/子型別組合是:application/x-www-form-urlencoded multipart/form-data text/plain。
application/json 不是一個簡單的請求。所以我不能為CORS情況發布json,但可以發布文本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/498363.html
標籤:javascript json 邮政 获取 API 云耀斑
上一篇:如何在文本視圖中顯示回應字串?
