访问 body 值时 Google 函数中断
2018-04-09
62
我想使用 google 函数来处理一些帖子数据并返回它。虽然它在本地运行良好,但我无法让它在 google 服务器上运行。
这个“函数”:
exports.helloWorld = (req, res) => {
res.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST');
res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.set('Access-Control-Allow-Origin', '*');
//res.status(200).send({"req.body.message": req.body.message});
res.status(200).send({"req.body.message.length": req.body.message.length});
return;
};
将因以下请求而失败:
fetch("https://us-central1-{myproject}.cloudfunctions.net/demo",
{
body: JSON.stringify({"message":"hello"}),
method: "POST",
headers: {
'Content-Type': 'application/json'
},
mode: "cors"
}
).then(response => response.json())
.then(d => console.log(d))
TypeError: Cannot read property 'length' of undefined
at exports.helloWorld (/user_code/index.js:17:76)
at ...
而使用注释掉的其他 res.status... 行的相同方法将起作用并返回 {req.body.message: "hello"
在本地这有效。。知道为什么会失败吗?
3个回答
问题是,我没有检查 request.method。浏览器发出了预检 OPTIONS 请求 - 而这个请求失败了,因为那里没有 req.body.message。所以真正的 POST 请求从未发生过。
这解决了它:
exports.helloWorld = (req, res) => {
if (req.method === 'POST') {
res.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST')
.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.set('Access-Control-Allow-Credentials', false)
.status(200).send({"req.body.message.length": req.body.message.length });
}
else {
res.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST')
.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.set('Access-Control-Allow-Credentials', false)
.status(200).send();
}
};
Michael
2018-04-10
尝试以下类似操作:
res.set('Access-Control-Allow-Origin', '*')
.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST')
.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
.set('Access-Control-Allow-Credentials', false)
.status(200).send({"req.body.message": req.body.message.length });
Mangu
2018-04-09
刚刚绞尽脑汁,cors 可以帮你轻松实现这个... 在你的 functions/index.js 中:
// import cors
const cors = require('cors')({origin: true});
exports.chat = onRequest(async (req, res) => {
cors(req, res, async () => {
try {
console.log(req.body)
console.log(req.body.data)
if (!req.body.data.message || !req.body.data.assistantId) {
return res.status(400).json({error: "Required field is missing"});
}
const userMessage = req.body.data.message;
const assistantId = req.body.data.assistantId;
<the rest of your code here>
Uros Randelovic
2024-04-18