如何正确配置我的 Cloudflare Worker 以将我发送的对象保存在 Cloudflare 的 KV(存储)中?
How do I properly configure my Cloudflare Worker to save my sent object in Cloudflare's KV (storage)?
我正在尝试将我博客上的新 post 作为 JS 对象保存到 Cloudflare 的 KV。
我编写了这个 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
这是来自我的前端的获取请求:
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);
});
}
};
我的 Cloudflare namespace/KV 中没有任何内容添加到数组 'posts'。
我认为它与数据类型有关。我不得不使用这个:
const body = await request.text()
因为我不知道如何处理预检请求。
当我点击保存时,这就是我在 Chrome 的控制台中得到的内容。
POST https://serverless-api.name.workers.dev/api/add 500
这是我在 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
}
您保存 KV 数据的方法是用名称 setCache
定义的,但在您的处理程序中您试图调用 setData
似乎是问题所在?
此外,对于预检请求,应该只是在发出传入 OPTIONS
请求时提前返回/跳过保存的问题(返回正确的 CORS headers)。
我正在尝试将我博客上的新 post 作为 JS 对象保存到 Cloudflare 的 KV。
我编写了这个 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
这是来自我的前端的获取请求:
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);
});
}
};
我的 Cloudflare namespace/KV 中没有任何内容添加到数组 'posts'。 我认为它与数据类型有关。我不得不使用这个:
const body = await request.text()
因为我不知道如何处理预检请求。
当我点击保存时,这就是我在 Chrome 的控制台中得到的内容。
POST https://serverless-api.name.workers.dev/api/add 500
这是我在 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
}
您保存 KV 数据的方法是用名称 setCache
定义的,但在您的处理程序中您试图调用 setData
似乎是问题所在?
此外,对于预检请求,应该只是在发出传入 OPTIONS
请求时提前返回/跳过保存的问题(返回正确的 CORS headers)。