首页 文章

将Express.js API部署到Heroku后出现CORS问题

提问于
浏览
0

我已经尝试了在CORS问题上找到的所有内容,但我似乎无法解决它 . 我正在使用带有Express.js API的React.js应用程序来处理邮件程序功能 . 在本地运行时,我确实得到了CORS问题并解决了这个问题:

const cors = require('cors')

app
  .use(cors())
  .use(bodyParser.urlencoded({ extended: true }))
  .use(bodyParser.json())
  .use(mailer)

我将React应用程序和Express API部署到Heroku,然后突然又开始出现CORS错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此,不允许来源“https:// ...”访问 . 响应具有HTTP状态代码503 .

所以我尝试了几种不同的方法来使它工作,但没有一个有用,一些例子:

app
  .use(bodyParser.urlencoded({ extended: true }))
  .use(bodyParser.json())
  .use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'https://florismeininger.herokuapp.com');
    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
      });
  .use(mailer)
app
  .use(cors({origin: 'https://florismeininger.herokuapp.com'}))
  .use(bodyParser.urlencoded({ extended: true }))
  .use(bodyParser.json())
  .use(mailer)
app
  .use(cors({origin: '*'}))
  .use(bodyParser.urlencoded({ extended: true }))
  .use(bodyParser.json())
  .use(mailer)

因此,对于预检OPTIONS请求,它是503错误 . 我通过使用multipart / form-data并附加正文来处理此请求:

var data = new FormData()
    data.append('body',body)

        api.post('/mailer', { attach: body })

现在我收到一个新的POST 503错误,还有这个错误:

无法加载https://florismeininger-mailer-api.herokuapp.com/mailer:请求的资源上没有'Access-Control-Allow-Origin'标头 . 原始'https://florismeininger.herokuapp.com ' is therefore not allowed access. The response had HTTP status code 503. If an opaque response serves your needs, set the request'模式到'no-cors'获取禁用CORS的资源 .

我也试过使用'no-cors'模式但是没有用 . 继续获取No'Access-Control-Allow-Origin' Headers 存在错误 .

1 回答

  • 0

    如果您在响应CORS预检OPTIONS请求时获得503,那么当@sideshowbarker发表评论时,问题是您的Web服务器(Apache或其他)可能不允许OPTIONS请求方法 .

相关问题