【问题标题】:Handling an OPTIONS request in a Keystone.js API在 Keystone.js API 中处理 OPTIONS 请求
【发布时间】:2015-10-16 23:13:57
【问题描述】:

我正在用 Keystone 支持的 Aurelia 构建一个 SPA。

从我的 Aurelia 视图发布时,Content-Type 设置为 application/json,这当然会在来自客户端时引发 OPTIONS 请求。

我的 Keystone 初始化设置在 cors 上为本地开发开放:

keystone.init({
    ...
    'cors allow origin': true,
    'cors allow methods': true,
    'cors allow headers': true,
    ...
});

我对 API 的 Keystone 路由绑定是:

exports = module.exports = function(app) {
    app.all('/api/*', keystone.middleware.cors);
    app.post('/api/inquiry', keystone.middleware.api, routes.api.inquiries.post);
};

我的 Keystone API 视图是:

var keystone = require('keystone'),
    Inquiry = keystone.list('Inquiry');

exports.post = function(req, res) {

    var inquiry = new Inquiry.model({
        name: {
            first: req.body.name.first,
            last: req.body.name.last
        },
        email: req.body.email,
        phone: req.body.phone,
        question: req.body.question
    });

    inquiry.save(function(error) {
        if (error) {
            return res.apiError(error);
        }

        return res.apiResponse({
            'inquiry': inquiry
        });
    });

};

我遇到的问题是 OPTIONS 请求 404s 而不是返回 200。

即使我手动处理 OPTIONS 请求并简单地返回状态 200,POST 请求也不会遵循 OPTIONS 请求。我是否误解了 OPTIONS 请求生命周期?

我也尝试过传入不同的内容类型,例如 'application/x-www-form-urlencodedtext/plain,并使用与这些格式匹配的数据,这不会导致 OPTIONS 请求,但 Keystone 不会解析这些 POST 的内容。

我做错了什么?

【问题讨论】:

    标签: rest keystonejs


    【解决方案1】:

    显然我错过了 Keystone 文档中的部分,您可以在其中自定义 Express 实例您将它交给 Keystone。

    // keystone.js
    
    var keystone = require('keystone');
    var express = require('express');
    var cons = require('consolidate');
    var nunjucks = require('nunjucks');
    var bodyParser = require('body-parser');
    var app = express();
    
    app.use(bodyParser.text());
    
    keystone.app = app;
    

    然后在我的 Aurelia 应用程序中,我调用 JSON.stringify(myObject),然后将其发布到 Keystone。随后在我的 Keystone 视图中,我只需将字符串解析回 JSON:

    exports.post = function(req, res, next) {
    
        if (!req.body) {
            return res.sendStatus(400);
        }
    
        var data = JSON.parse(req.body),
            inquiry = new Inquiry.model(data);
    
        inquiry.save(function(error) {
            if (error) {
                return res.apiError(error);
            }
    
            return res.apiResponse({
                'inquiry': inquiry
            });
        });
    
    };
    

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 2010-09-18
      • 2018-01-03
      • 2013-02-02
      • 2019-09-17
      • 2016-01-24
      • 2021-09-26
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多