Firebase函数返回400

时间:2018-10-10 21:04:02

标签: node.js firebase post google-cloud-functions

我面临一个非常奇怪的问题。我是一名使用Firebase函数作为班级应用程序后端的讲师,并且我的两个学生遇到了我没有的相同问题:

我的前端对Firebase函数进行了后期调用,该函数访问了IBM WAtson并给出了答案。

重点是,它对我来说很好,当我与他们共享端点时,他们的代码有效,当他们与我共享端点时,我的前台总是失败400。 我无法解释发生了什么。进入api后,我们所有的代码都能很好地返回。

这是我的工作网址:SO thread'

这是我的一位学生的网址,带有控制台日志:

Request URL: https://us-central1-chatbot-react.cloudfunctions.net/conversa
Request Method: POST
Status Code: 400 
Remote Address: 172.217.11.46:443
Referrer Policy: no-referrer-when-downgrade
access-control-allow-origin: http://localhost:3000
alt-svc: quic=":443"; ma=2592000; v="44,43,39,35"
cache-control: private
content-encoding: gzip
content-length: 159
content-type: application/json; charset=utf-8
date: Wed, 10 Oct 2018 20:51:19 GMT
etag: W/"a8-3BNzCKPhycJhIXE/IBTFVDjBiN0"
function-execution-id: 0fye621c7drg
server: Google Frontend
status: 400
vary: Origin
x-cloud-trace-context: c7353ce928ae47283e9a248dc2cf2147
x-powered-by: Express
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: http://localhost:3000
Referer: http://localhost:3000/
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
{input: "reginaldo", context: {conversation_id: "6a012cbd-d0af-44b3-982d-7b2d6c81b4e9",…}}
context: {conversation_id: "6a012cbd-d0af-44b3-982d-7b2d6c81b4e9",…}
input: "reginaldo"

我们是否缺少许可? 这是我们正在使用的代码:

const functions = require('firebase-functions');
const watson = require('watson-developer-cloud/assistant/v1')
require('dotenv').config()

const cors = require('cors')({ origin: true })

const chatbot = new watson({
    username: process.env.USERNAME,
    password: process.env.PASSW0RD,
    version: process.env.VERSION,
});

const workspace_id = process.env.WORKSPACE_ID;

exports.conversa = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        let payload = {
            workspace_id,
            context: req.body.context || {},
            input: req.body.input || {}
        };

        chatbot.message(payload, (err, data) => {
            if (err) {
                return res.status(err.code || 500).json(err);
            }

            return res.json(trataResposta(payload, data));
        })
    })
})

const trataResposta = (payload, resposta) => {
    console.log('watson disse: ', resposta.output.text[0]);
    return resposta;
}

我们感谢您提供的帮助。

1 个答案:

答案 0 :(得分:1)

认为它应该在不支持cors ... req.method POST的情况下工作:

exports.conversa = functions.https.onRequest((req, res) => {
    let payload = {
        workspace_id,
        context: req.body.context || {},
        input: req.body.input || {}
    };
    chatbot.message(payload, (err, data) => {
        if (err) {
            return res.status(err.code || 500).json(err);
        }
        return res.json(trataResposta(payload, data));
    });
});

请参见Cross-Origin Resource Sharing (CORS)