【发布时间】:2020-11-28 20:17:23
【问题描述】:
我正在尝试使用 Javascript fetch 和 application/json 作为 content-type 发送 POST 请求,但遇到了问题。当我在邮递员中提出请求时,它工作正常。当我尝试通过 Javascript fetch 执行此操作时,我收到一个错误,并且在 GCF 日志记录方面,当我尝试记录 console.log(req.body) 时,没有注册任何内容。
当我将请求 content-type 更改为 text/plain 然后在我的云函数中解析 JSON 时,我能够成功地显示并注册请求正文,但我想删除它如果可能的话,额外的步骤(并找出为什么这不起作用)。
这是客户端获取请求(基本上是从 Postman 粘贴的),由于某种原因,正文没有通过,我尝试了从属性名称中删除引号并删除 stringify 的各种组合:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"key1":"value1","key2":"value2"});
var requestOptions = {
method: 'post',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("mycloudfunctionsurl", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
这是我的 Node.JS 运行时 10 云函数代码:
exports.helloHttp = async ( req, res ) => {
res.set('Access-Control-Allow-Origin', '*');
console.log(req.body); // <-- Shows up with Postman but not above code, unless I change to text/plain
var key1 = req.body.key1;
console.log('key1 is ' + key1);
// other functions to process the response body
};
【问题讨论】:
-
您是否也在此处尝试满足 CORS 要求?
-
嗨@DougStevenson,我在客户端遇到的错误是CORS错误,但我之前从http请求收到这些错误作为一般错误,在这种情况下也是POST请求使用不同的内容类型正在工作,所以我认为它与 CORS 无关。这实际上是与内容类型为 JSON 相关的 CORS 问题吗?如果是这样,我该如何解决?为了回答您的问题,请求来自不同的来源。谢谢。
标签: javascript json post google-cloud-functions fetch