仍然無法弄清楚這個 Cors 的東西很煩人。嘗試測驗將文本從輸入發送到 twilio。我想從我的手機發短信到一個動態號碼。無論我做什么,我都會不斷收到 cors 錯誤?我肯定做錯了什么,我不允許從本地主機發送嗎?
SVELTE 應用程式
let phoneNumber = "";
const handleSendText = () => {
fetch("https://svelte-service-9106.twil.io/sms", {
method: "POST",
body: JSON.stringify({
to: phoneNumber,
from: " 11111111111",
}),
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
if (!response.ok) {
throw new Error("failed");
}
})
.catch((err) => {
console.log(err);
});
};
<input type="text" bind:value={phoneNumber} />
<button on:click={handleSendText}>Send</button>
TWILIO 功能
exports.handler = async function (context, event, callback){
const twilioClient = context.getTwilioClient();
const messageDetails = {
body: "Ahoy, Svelte developer!",
to: event.to,
from: event.from,
}
const response = new Twilio.Response();
const headers = {
"Access-Control-Allow-Origin" : "http://localhost:5000",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS",
"Content-Type": "application/json"
};
response.setHeaders(headers);
try {
const message = await twilioClient.messages.create(messageDetails);
response.setBody({
status: `Your message was sent successfully with SID: ${message.sid}`
});
return callback(null, response);
} catch(error) {
response.setBody({
status: error
});
return callback(response);
}
}
錯誤

uj5u.com熱心網友回復:
我剛剛復制了您的函式,將其部署到我自己的 Twilio 帳戶,并且能夠fetch從localhost:5000.
但是,如果我導致錯誤,例如使用不正確的from數字,則會收到 CORS 錯誤。問題是您的函式將response物件作為callback函式的第一個引數回傳。該引數保留用于錯誤物件,而不是用于回應,并且 Twilio Functions 將在接收到錯誤作為回呼函式的第一個引數時創建自己的回應。該回應不包括 CORS 標頭,因此您會收到 CORS 錯誤。
處理這個問題的方法是發送您的回應并自己設定狀態代碼。
因此,將您的功能更新為:
try {
const message = await twilioClient.messages.create(messageDetails);
response.setBody({
status: `Your message was sent successfully with SID: ${message.sid}`
});
return callback(null, response);
} catch(error) {
response.setBody({
status: error.message
});
response.setStatusCode(400);
return callback(null, response);
}
您可以看到,在該catch塊中,我將狀態代碼設定為 400 并將回應物件作為回呼的第二個引數回傳。
現在,你的前端代碼也沒有暴露你會從中得到的錯誤,主要是因為當回應不正確時它會拋出自己的例外。status嘗試更新以決議錯誤正文并使用您在錯誤中設定的屬性引發錯誤。
fetch("https://svelte-service-9106.twil.io/sms", {
method: "POST",
body: JSON.stringify({
to: phoneNumber,
from: " 111111111111",
}),
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
if (!response.ok) {
response.json().then((body) => {
throw new Error(body.status);
})
} else {
console.log("Success"); }
})
.catch((err) => {
console.log(err);
});
一旦你像這樣更新你仍然會得到一個錯誤,但錯誤將包含來自 API 的錯誤訊息,你將能夠修復它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448882.html
標籤:api 科尔斯 暮光之城 http-post twilio-api
