简体   繁体   English

为什么前端从快速服务器接收空对象?

[英]Why is frontend receiving an empty object from express server?

Trying to figure out how to implement this request and response scenario with javascript's fetch() and an express server.试图弄清楚如何使用 javascript 的fetch()和一个快速服务器来实现这个请求和响应场景。

here's the server:这是服务器:

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);

here's routes/connect:这是路线/连接:

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;

here's the fetch POST:这是获取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()
   })
  }

The express server logs Firebase Update Success快速服务器记录Firebase Update Success

the front end logs:前端日志:

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

Just trying to figure out how to properly get this response from express.只是想弄清楚如何正确地从快递那里得到这个回应。 Not sure what all of these log-symptoms are telling me.不确定所有这些日志症状告诉我什么。 just figured id log all the different ways I could think of handling the response object.只是想 id 记录了我能想到的处理响应对象的所有不同方式。

What do I need to do to get the response data?我需要做什么来获取响应数据?

Your .then() function is just a promise because your receiving it as soon as you get the headers from the request, you need to send the response back (res.send()) in the .then() of the res.json() because it is also a promise.您的 .then() 函数只是一个承诺,因为一旦您从请求中获取标头就收到它,您需要在 res.json 的 .then() 中将响应发送回 (res.send()) () 因为它也是一个承诺。 so that modify your routes/connect as per below.以便按照以下方式修改您的路线/连接。

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 });
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM