gpt4 book ai didi

javascript - 无法从 React 前端向 Node.js 后端发送 POST 请求

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:29 25 4
gpt4 key购买 nike

我有一个简单的 Node.js 作品集页面,其中包含一个联系页面,我使用第三方 API 来发送电子邮件 (sendgrid)。 sendgrid API 查询的信息保存到 sendgridObj 中,并在提交联系表单后向我的服务器 server.js 发出 POST 请求。

//CONTACT.JS PAGE

emailApi = () => {
let sendgridObj = {
to: 'caseyclinga@gmail.com',
from: this.state.from,
subject: this.state.subject,
text: this.state.text
}
this.resetState();
axios.post('/contact', sendgridObj)
.then(res => console.log(`CONTACT.JS RESPONSE: ${res}`))
.catch(err => console.log(`CONTACT.JS ERROR: ${err}`));
}

在后端,我设置了 /contact 的路由,并使用 sendgridObj 发出 POST 请求来发送grid 邮件。

//SERVER.JS FILE

const express = require('express');
var app = express();
const SgMail = require('@sendgrid/mail');
const path = require('path');

SgMail.setApiKey(process.env.REACT_APP_SENDGRID_API_KEY);

//Middleware stuff

app.post('/contact', (req, res) => {
console.log(req.body)
SgMail.send(req.body)
.then(res => console.log(JSON.stringify(res, null, 2)))
.catch(err => console.log(`SERVER.JS ERROR: ${err}`));
});

app.listen(PORT, () => console.log(`Server running on port ${PORT}`))

所有相对简单的东西。这一切都运行良好,直到几天前它莫名其妙地停止运行。当我在后端运行 console.log(req.body) 时,它会显示我发送的对象,因此这不是 req.body 的问题。这也不是我的 API key 的问题,我在来自 Sendgrid 的响应对象中收到 202(未捕获任何错误)。

但是,在提交联系表单后大约 45 秒左右,前端捕获了 500 错误 POST http://localhost:3000/contact 500(内部服务器错误)。然后我注意到,如果我重置服务器,我的后端会出现代理错误 代理错误:无法将请求/contact 从 localhost:3000 代理到 http://localhost:5000/。

所以看来我的路线有问题,或者以某种方式向 Sendgrid 发送请求有问题,但我完全不明白为什么。我可以控制台记录查询对象以显示它正在发送到后端,然后我收到 202 响应,但仍然收到错误?如果它无法代理我的请求,那么为什么仍然发送该对象?

这是我的完整代码:https://github.com/caseycling/portfolio

最佳答案

您应该为后端和前端创建 baseURL。示例:

const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});

然后,您应该使用创建的实例来获取或发布与后端集成。

关于javascript - 无法从 React 前端向 Node.js 后端发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60180192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com