【问题标题】:gatsbyjs and expressjs Error 400 Bad Request while fetch获取时 gatsbyjs 和 expressjs 错误 400 错误请求
【发布时间】:2021-06-19 14:20:09
【问题描述】:

我有一个带有 ExpressJS 的小型后端,可以发送电子邮件,我已经在 Heroku 网站上部署了这个后端,我已经用邮递员尝试过,一切正常,它可以工作,但是当我想要的时候要从我的 gatsby 站点使用它,它会引发 cors 问题,gatsby 站点正在我的本地主机上运行。

ExpressJS 代码:

import dotenv from 'dotenv';
import express from 'express';
import nodemailer from 'nodemailer';
import cors from 'cors';

if (process.env.NODE_ENV !== 'production') {
  dotenv.config();
}

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(cors());

const contactAddress = process.env.CONTACT_ADDRESS || '';

const mailer = nodemailer.createTransport({
  service: 'Gmail',
  auth: {
    user: process.env.GMAIL_ADDRESS,
    pass: process.env.GMAIL_PASSWORD,
  },
});

app.post('/contact', (req, res) => {
  if (!req.body.from)
    return res.status(400).json({ message: 'From is required' });
  if (!req.body.message)
    return res.status(400).json({ message: 'Message is required' });
  mailer.sendMail(
    {
      from: req.body.from,
      to: [contactAddress],
      subject: 'Contact from API',
      html: `<h3>${req.body.from}</h3><br>${req.body.message}`,
    },
    (err, info) => {
      if (err) {
        console.log(err);
        return res.status(500).send(err);
      }
      res.status(200).json({ success: true });
    }
  );
});

app.listen(process.env.PORT || 8000);
console.log(`App running on port ${process.env.PORT || 8000}`);

发出请求的前端代码:

const onSubmit = async (data: IFormInputs) => {
    console.log(data);
    const formData = new FormData();
    Object.keys(data).forEach((el) => {
      formData.append(el, data[el]);
    });

    try {
      const res = await fetch(`${BACKEND_URL}contact`, {
        method: 'POST',
        body: formData,
      });

      console.log(res);
    } catch (e) {
      console.log(e);
    }
  }

我也尝试在 fetch 上添加一些配置,但它无论如何都不起作用

const res = await fetch(`${BACKEND_URL}contact`, {
            method: 'POST',
            mode: 'cors',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json',
          },
          referrerPolicy: 'origin', 
            body: formData,
          });

错误抛出以下错误:

{
 status: 400,
 statusText: "Bad Request",
 type: "cors",
 ok: false,
}

我在 StackOverflow 上搜索过类似的问题,但任何解决方案都对我有用。

this post 上的答案对我不起作用,因为我在 localhost 上没有后端和前端,我正在使用 Heroku 站点上的 API。

提前致谢!

【问题讨论】:

  • 这能回答你的问题吗? React + Express CORS error 400 Bad Request
  • @Taki 不,我也尝试过这个解决方案,我认为这个问题在 localhost 上有前端和后端,那是因为他们使用 package.json 上的代理,同时我的后端托管在一个heroku网站,我已经在我的package.json前端添加了"proxy": "http://localhost:8000",我也有同样的错误。

标签: node.js reactjs express gatsby


【解决方案1】:
  1. 您正在侦听端口8000。你确定它是正确的吗?让我们试试8080 的帖子。
  2. 您还可以设置标题:
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

【讨论】:

  • 后端监听 Heroku 环境变量中列出的端口,当我用邮递员获取时,我只写主机名和操作'/contact',我不写任何端口,所以我不认为这是必要的。而且我认为 cors() 中间件正在设置所有这些配置,我需要再次进行所有设置吗?
猜你喜欢
  • 2017-11-27
  • 2011-03-09
  • 2017-12-31
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 2017-08-04
相关资源
最近更新 更多