[英]How do I properly configure my Cloudflare Worker to save my sent object in Cloudflare's KV (storage)?
I am trying to save a new post on my blog as JS Object to Cloudflare's KV.我正在尝试将我博客上的新帖子作为 JS 对象保存到 Cloudflare 的 KV。
I wrote this Cloudflare's Worker code to respond to 'POST' methods.我编写了这个 Cloudflare 的 Worker 代码来响应“POST”方法。
const setCache = (key, data) => name_data.put(key, data)
const getCache = key => name_data.get(key)
async function Create(request) {
const body = await request.text()
const dataKey = `posts`
const headers = {
Allow: 'OPTIONS, GET, HEAD, POST',
'Access-Control-Allow-Origin': '*',
'Content-type': 'application/json',
}
try {
// JSON.parse(body)
await setData(dataKey, body)
return new Response(body, { status: 200, headers: headers })
} catch (err) {
return new Response(err, { status: 500, headers: headers })
}
}
export default Create
Here is the fetch request from my frontend:这是来自我的前端的获取请求:
const onSavePostClicked = async () => {
if (canSave) {
const data = { title, content, author, id: nanoid() };
fetch('https://serverless-api.mySpace.workers.dev/api/add', {
method: 'POST',
headers: {
// 'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response)
.then((data) => {
console.log('Success:', data);
setTitle('');
setContent('');
setAuthor('');
})
.catch((error) => {
console.error('Error:', error);
});
}
};
Nothing gets added to array 'posts' in my Cloudflare's namespace/KV.我的 Cloudflare 的命名空间/KV 中的数组“posts”中没有添加任何内容。 I think it has something with the types of the data.
我认为它与数据类型有关。 I had to use this:
我不得不使用这个:
const body = await request.text()
because I don't know how to handle preflight requests.因为我不知道如何处理预检请求。
When I hit save, this is what I get in my Chrome's console.当我点击保存时,这就是我在 Chrome 控制台中得到的。
POST https://serverless-api.name.workers.dev/api/add 500
And this is what I get in Cloudflare's Worker log:这就是我在 Cloudflare 的 Worker 日志中得到的信息:
"outcome": "ok",
"scriptName": null,
"exceptions": [],
"logs": [],
"eventTimestamp": 1637022226250,
"event": {
"request": {
"url": "https://serverless-api.name.workers.dev/api/add",
"method": "POST",
"headers": {
"accept": "*/*",
"accept-encoding": "gzip",
"accept-language": "en-US",
"cf-connecting-ip": "",
"cf-ipcountry": "US",
"cf-ray": "",
"cf-visitor": "{\"scheme\":\"https\"}",
"connection": "Keep-Alive",
"content-length": "87",
"content-type": "text/plain;charset=UTF-8",
"host": "serverless-api.name.workers.dev",
"origin": "http://localhost:3000",
"referer": "http://localhost:3000/",
"sec-ch-ua": "\"Google Chrome\";v=\"95\", \"Chromium\";v=\"95\", \";Not A Brand\";v=\"99\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "cross-site",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36",
"x-forwarded-proto": "https",
"x-real-ip": ""
},
"cf": {
"longitude": "",
"latitude": "",
"tlsCipher": "",
"continent": "NA",
"asn": 7922,
"clientAcceptEncoding": "gzip, deflate, br",
"country": "US",
"tlsClientAuth": {
"certIssuerDNLegacy": "",
"certIssuerSKI": "",
"certSubjectDNRFC2253": "",
"certSubjectDNLegacy": "",
"certFingerprintSHA256": "",
"certNotBefore": "",
"certSKI": "",
"certSerial": "",
"certIssuerDN": "",
"certVerified": "NONE",
"certNotAfter": "",
"certSubjectDN": "",
"certPresented": "0",
"certRevoked": "0",
"certIssuerSerial": "",
"certIssuerDNRFC2253": "",
"certFingerprintSHA1": ""
},
"tlsVersion": "TLSv1.3",
"edgeRequestKeepAliveStatus": 1,
"requestPriority": "",
"httpProtocol": "HTTP/3",
}
}
},
"id": 0
}
Your method to save KV data is defined with name setCache
but in your handler you are attempting to call setData
seems like the issue?您保存 KV 数据的方法是用名称
setCache
定义的,但是在您的处理程序中,您尝试调用setData
似乎是问题所在?
Also, for preflight requests, should just be a matter of returning early / skipping save when an incoming OPTIONS
request is made (returning the correct CORS headers).此外,对于预检请求,应该只是在发出传入
OPTIONS
请求(返回正确的 CORS 标头)时提前返回/跳过保存的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.