Axios.post 在 API 调用后返回:ERR_EMPTY_RESPONSE

Axios.post returning :ERR_EMPTY_RESPONSE after API call

我在我的 React 组件中发出了一个 axios post 请求,该请求向 twilio 发出了从我服务器上的路由向我的 phone 发送短信的请求.

短信和有效负载已成功传输,但是在控制台中打开网络选项卡时,我在一两分钟内收到此错误。

POST http://localhost:8080/api/twilio net::ERR_EMPTY_RESPONSE

有什么解决办法吗?

这是我的反应组件的代码:

import React, { Component } from 'react';
import axios from 'axios';
import { Grid, Segment, Form } from 'semantic-ui-react';
import './test.css';

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { phonenumber: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ phonenumber: event.target.value });
  }

  handleSubmit() {
    return axios
      .post('/api/twilio', {
        phonenumber: this.state.phonenumber,
      })
      .then(resp => resp.data)
      .catch(error => console.log(error));
  }

  render() {
    const { phonenumber } = this.state;
    console.log('phonenumber', phonenumber);

    return (
      <Grid columns={1} stackable textAlign="center">
        <Grid.Column width={1} />
        <Grid.Column width={14}>
          <Form onSubmit={this.handleSubmit}>
            <Segment stacked>
              <Form.Group id="form-group" inline>
                <label>Phone Number</label>
                <Form.Input onChange={this.handleChange} value={phonenumber} placeholder="+12223334444" />
              </Form.Group>
              <Form.Button id="form-group-button" content="Submit" />
            </Segment>
          </Form>
        </Grid.Column>
        <Grid.Column width={1} />
      </Grid>
    );
  }
}

export default Test;

更新:

这是后端的 twilio 路由。

const router = require('express').Router();

module.exports = router;

router.post('/', (req, res) => {
  let SID = 'ACc5b16ad0cefc3b514e69bc30636726e2';
  let TOKEN = '3145fb41afe308f22b0b7c647e6a8e17';
  let SENDER = '+18622256079';

  if (!SID || !TOKEN) {
    return res.json({ message: 'add TWILIO_SID and TWILIO_TOKEN to .env file.' });
  }

  let client = require('twilio')(SID, TOKEN);

  client.messages
    .create({
      to: req.body.phonenumber,
      from: SENDER,
      body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
    })
    .then(message => console.log(message.sid));
});

在服务器上的路由中,不会向客户端返回任何内容,因为 SIDTOKEN 始终已定义(至少在您的示例中)。为确保请求不会失败,您需要在 Twilio 请求后至少发回一些响应,例如:

client.messages
  .create({
    to: req.body.phonenumber,
    from: SENDER,
    body: 'This is the ship that made the Kessel Run in fourteen parsecs?'
  })
  .then(message => {
    console.log(message.sid);

    // Either just send an empty, successful response or some data (e.g. the `sid`)
    res.status(200).send(message.sid);
  })
  .catch(err => {
    console.log(err);

    // In case of an error, let the client know as well.
    res.status(500).send(err);
  });