【问题标题】:Why is frontend receiving an empty object from express server?为什么前端从快递服务器接收一个空对象?
【发布时间】:2020-03-13 03:05:22
【问题描述】:

试图弄清楚如何使用 javascript 的 fetch() 和一个快速服务器来实现这个请求和响应场景。

这是服务器:

var express = require('express'),
    stripeConnect = require('./routes/connect'),
    cors = require('cors'),
    bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(cors());

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

app.use('/connect', connect);

app.listen(process.env.PORT || 5000);

这里是路线/连接:

const express = require('express');
const router = express.Router();
const admin = require('firebase-admin');
admin.initializeApp({
    credential: admin.credential.cert({
        projectId: process.env.projectId,
        clientEmail: process.env.clientEmail,
        privateKey: process.env.privateKey.replace(/\\n/g, '\n'),
        clientId: process.env.clientId
    }),
    databaseURL: process.env.databaseURL
});

const STRIPE_SK = 'sk_test_KEY';
const stripe = require('stripe')(STRIPE_SK);

// @route POST /stripeConnect/link
// @desc save stripe user account id to their firebase profile
// @access public
router.post('/link', (req, res) => {
    console.log('\nLINK-REQUEST-BODY => ');
    console.log(req.body);

    return admin
        .firestore()
        .collection('users')
        .doc(req.body.docId)
        .update({ stripeId: 'test_Id' })
        .then((success) => {
            console.log('Firestore Update: Success');
            res.json({ msg: 'Stripe account ID added to Slide profile.' });
        })
        .catch((err) => {
            console.log('Firestore Update: Fail, Error: ' + err.message);
            res.json({ msg });
        });
});

module.exports = router;

这里是获取 POST:

 function submit() {
   $("#progress-label").text("Working...")

   const request = {
     method: "POST",
     body: JSON.stringify({
       docId: $('#id').val(),
       stripeId: USER_ID
     }),
     mode: 'cors',
     headers: { 'Content-Type': 'application/json'}
   }
   fetch(SERVER_URL + "/link", request).then(res => {
     console.log("res => " + res)
     console.log("res.json() => "+ res.json())
     console.log("JSON.stringify(res.json()) => "+ JSON.stringify(res.json()))
     console.log("res.data => " + res.data)
     console.log("res.msg" => + res.msg
   }).catch(err => {
     document.getElementById("label").innerHTML = res.json()
   })
  }

快递服务器日志Firebase Update Success

前端日志:

res => [object Response]
res.json() => [object Promise]
JSON.stringify(res.json()) => {}
res.data => undefined
res.msg => undefined

只是想弄清楚如何正确地从 express 获得此响应。不确定所有这些日志症状告诉我什么。只是想 id 记录我能想到的处理响应对象的所有不同方式。

我需要做什么才能获得响应数据?

【问题讨论】:

  • 您需要再添加一个 .then() 因为您的 res.json() 也是一个承诺。检查下面的答案

标签: javascript node.js express response


【解决方案1】:

您的 .then() 函数只是一个承诺,因为您在从请求中获取标头后立即收到它,您需要在 .then() 中将响应发送回 (res.send()) res.json() 因为它也是一个承诺。以便按照以下方式修改您的路线/连接。

router.post('/link', (req, res) => {
    console.log('\nLINK-REQUEST-BODY => ');
    console.log(req.body);

    return admin
        .firestore()
        .collection('users')
        .doc(req.body.docId)
        .update({ stripeId: 'test_Id' })
        .then((success) => {
            console.log('Firestore Update: Success');
            res.json().then(data => ({
                data: data,
                status: response.status
            })
            ).then(res => {
            console.log(res.status, res.data)
            })
        .catch((err) => {
            console.log('Firestore Update: Fail, Error: ' + err.message);
            res.json({ msg });
        });
});

【讨论】:

  • 按照您建议的修改,完全不更改前端代码,结果如下:前端错误:Uncaught (in promise) SyntaxError: Unexpected end of JSON inputUncaught (in promise) TypeError: Failed to execute 'json' on 'Response': body stream is locked 和服务器端日志为:Firestore Update: Success 2020-03-13T21:13:26.035495+00:00 app[web.1]: Firestore Update: Fail, Error: res.json(...).then is not a function
猜你喜欢
  • 2019-09-17
  • 1970-01-01
  • 2016-06-27
  • 2019-12-31
  • 1970-01-01
  • 2021-12-14
  • 2014-08-20
  • 1970-01-01
  • 2021-10-15
相关资源
最近更新 更多