heroku发送邮件接收为选项

nkhmeac6  于 2022-11-13  发布在  其他
关注(0)|答案(2)|浏览(226)

我已经在Heroku上部署了一个API,当我从我的网站发送帖子请求时,Heroku日志显示method=options,并且不起作用。当我从我的本地机器发送帖子时,Heroku日志显示method=post,并且一切都很好。
我在StackOverflow Heroku use Options instead of POST method中找到了这篇文章,但该解决方案并没有解决我的问题。
Heroku日志,首先是来自本地,其次是来自网站:

2022-10-06T23:57:19.315699+00:00 heroku[router]: at=info method=POST path="/api/smsNotif/applySmsNotif" host=***** request_id=88da98c7-f136-4775-a52a-b10b104b2cff fwd="****" dyno=web.1 connect=0ms service=11ms status=200 bytes=462 protocol=https

2022-10-07T00:01:05.970299+00:00 heroku[router]: at=info method=OPTIONS path="/api/smsNotif/applySmsNotif" host=***** request_id=039a51c3-a976-47f7-bd03-4c52bc71361f fwd="****" dyno=web.1 connect=0ms service=1ms status=204 bytes=277 protocol=https

我的请求来自一个托管网站上的axios:

api({
        method: "POST",
        url: "/api/smsNotif/applySmsNotif",
        data: appData,
      });

修复方法=选项的API代码:

const app = express();

app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
app.use(express.json());
app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    // handle OPTIONS method
    if ('OPTIONS' == req.method) {
        return res.sendStatus(200);
    } else {
        next();
    }
});
kt06eoxx

kt06eoxx1#

句柄选项方法只在没有cors模块的情况下才能工作。当你使用cors模块时,你需要做以下修改。

const app = express();

app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
app.options('*', cors()) // include before other routes

如果你面临CORS错误,那么通过删除origin和test来改变cors配置。

app.use(cors())
cgvd09ve

cgvd09ve2#

经过几次重新加载后,原始代码正常工作,从(Heroku use Options instead of POST method
感谢您发送编修。
有一点需要注意:

app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))

我在多个应用程序中使用我的API,我需要在上面的代码中为CORS列出所有这些应用程序。

const app = express();

app.use(cors({ origin: ['https://forms.ccenttcs.com/', 'http://localhost:9002'], }))
app.use(express.json());
app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    // handle OPTIONS method
    if ('OPTIONS' == req.method) {
        return res.sendStatus(200);
    } else {
        next();
    }
});

相关问题