Reactjs 与express server联系,在邮件中给我400
我不明白为什么我总是拿400分,这让我发疯 在my express服务器中:Reactjs 与express server联系,在邮件中给我400,reactjs,express,Reactjs,Express,我不明白为什么我总是拿400分,这让我发疯 在my express服务器中: const app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.post('/api/messages', (req, res) => { console.log(req.body.body) res.header('Content-Type', 'ap
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/api/messages', (req, res) => {
console.log(req.body.body)
res.header('Content-Type', 'application/json');
client.messages
.create({
from: process.env.TWILIO_PHONE_NUMBER,
to: '13105551212',
body: req.body.body
})
.then(() => {
res.send(JSON.stringify({ success: true }));
})
.catch(err => {
console.log(err);
res.send(JSON.stringify({ success: false }));
});
});
这是在根目录中,我在端口5000上运行它。本地主机:5000
我只是想看看我是否打了服务器
在子目录client
中,我有一个react build文件夹,可以在其中加载前端。我在这里运行这个方法: this.state.method='hi this is test'
export function twilioSend(event) {
event.preventDefault();
this.setState({ submitting: true });
fetch('/api/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state.message)
})
.then(res => res.text()) // convert to plain text
.then(text => console.log(text))
}
在“我的网络”选项卡中:
Request URL: http://localhost:5000/api/messages
我得到的错误是:
SyntaxError: Unexpected token " in JSON at position 0
知道我做错了什么吗?在您的服务器中,作为对象发送:
res.send({ success: true });
及
在前端,获取以下信息:
fetch('/api/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: this.state.message })
})
.then(res => res.json())
请为this.state.message创建post示例值,或者创建一个有相同问题的项目。
fetch('/api/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: this.state.message })
})
.then(res => res.json())