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

时间:2020-02-12 02:23:44

标签: javascript node.js reactjs

我有一个简单的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请求以发送网格邮件。

//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密钥也不是问题,并且我在Sendgrid的响应对象中收到202(不发生任何错误)。

但是,在提交联系表后大约45秒钟左右,前端捕获到500错误POST http://localhost:3000/contact 500 (Internal Server Error)。 然后,我注意到如果重置服务器,后端Proxy error: Could not proxy request /contact from localhost:3000 to http://localhost:5000/.

会收到代理错误

因此,我的路线似乎有问题,或者将请求发送至Sendgrid时遇到了问题,但是我对原因完全感到困惑。我可以控制台记录查询对象,以显示它正在发送到后端,然后得到202响应,但是仍然出现错误?如果无法代理我的请求,那么为什么仍发送该对象?

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

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

好像您的React服务器和Node js服务器在不同的端口上运行。

您需要处理的两件事是:

  • 指定完整的baseURL到节点js后端
  • 为节点js添加cors配置并运行

    npm install cors

然后将其添加到您的node.js代码中

var cors = require('cors')

var app = express()

app.use(cors())