我正在编写一个程序,其中用户在React前端中输入一个数字,而Node.js Express后端将在用户编号下获取所有可能的质数,并以该质数数组的中值元素作为响应。

服务器正常工作,并且前端成功向服务器发送了一个号码,但是当我在控制台中打印该服务器时,服务器响应为:

Promise { <state>: "pending" }
undefined


我究竟做错了什么?

前端React组件:

import React, {Component} from 'react';

class NumberInputField extends Component {

    constructor() {
        super();
        this.state = {
            number: 0,
            errorText: ''
        }

        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onChange(e) {
        this.setState({[e.target.name]:e.target.value});
    }

    onError(errText) {
        this.setState((previousState, props) => {
            return { errorText: errText}
        })
    }

    onSubmit(e) {
        e.preventDefault();
        console.log("> Submitting form");
        //console.log(this.state);

        fetch('http://localhost:3000/setprime', {
            method: 'POST',
            body: JSON.stringify(this.state),
        })
        .then(r => {
            console.log(r.json());
        })
        .then(data => {
            console.log(data);
        })
        .catch(e => {
            console.log(e);
            this.onError(e.toString());
        })
    }

    render() {
        return (
            <div>
                <form onSubmit={this.onSubmit}>
                    <input type="text" name="number" onChange={this.onChange}/>
                    <input type="submit" value="Submit"/>
                </form>
                <p className="errorLabel">{this.state.errorText}</p>
            </div>
        );

    }

}

export default NumberInputField;


server.js

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var serverhelpers = require("./serverhelpers");
var cors = require("cors");

app.use(cors());

app.use ( bodyParser.json( { type: "*/*" } ));

app.post("/setprime", (req, res) => {
    console.log(req.body);
    console.log("Received number " + req.body.number + " from frontend");

    let primes = getAllPrimes(req.body.number);
    let median = getMedianArray(primes);

    console.log("Primes: " + primes);
    console.log("Median: " + median);

    res.setHeader("Content-type", "application/json");
    return res.send(median);
});

app.listen(3000);
console.log("Server listening on port 3000.");


谢谢

最佳答案

问题出在:

.then(r => {
  console.log(r.json());
})

r.json()the return valuePromise
您必须退还:
.then(r => {
  //console.log(r.json());
  return r.json();
})

您应该看到data之后登录。

关于javascript - 来自Express的响应未定义且未决(React前端),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58561014/

10-13 00:29