我在我的react组件中发出了一个axios post
请求,该请求向twilio
请求从我服务器上的路由向我的手机发送短信。
文本消息和有效负载已成功传输,但是在控制台中打开网络选项卡时,我会在一两分钟内收到此错误。
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));
});
答案 0 :(得分:1)
在服务器上的路由中,不会将任何内容返回给客户端,因为始终定义SID
和TOKEN
(至少在您的示例中)。为了确保请求不会失败,您需要在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);
});