Node.js Restify仅接受get方法,即使来自同一域

Node.js Restify仅接受get方法,即使来自同一域,node.js,restify,Node.js,Restify,我在restify中遇到了一个问题。我只能在API中使用get方法。通常情况下,当涉及CORS时,人们似乎遇到了问题,但我甚至不能将其用于同一领域。我已经尝试了很多,并且在localhost的同一个域中使用了一段时间 但后来我修改了我的代码,但它不起作用。此外,我似乎无法获取POST请求的req.body或req.params中的参数。我也没有使用任何飞行前请求 'use strict'; var restify = require('restify'), plugins = require('

我在restify中遇到了一个问题。我只能在API中使用get方法。通常情况下,当涉及CORS时,人们似乎遇到了问题,但我甚至不能将其用于同一领域。我已经尝试了很多,并且在localhost的同一个域中使用了一段时间

但后来我修改了我的代码,但它不起作用。此外,我似乎无法获取POST请求的req.body或req.params中的参数。我也没有使用任何飞行前请求

'use strict';
var restify = require('restify'),
plugins = require('restify-plugins'),
config = require('./config.js'),
personController = require('./routes/person-controller')


var server = restify.createServer({
name: config.name,
version: config.version,
})


server.use(plugins.jsonBodyParser({ mapParams: true }))
server.use(plugins.acceptParser(server.acceptable))
server.use(plugins.queryParser({ mapParams: true }))
server.pre(restify.CORS({
origins: [
    '*'
],
headers: [
    "authorization",
    "withcredentials",
    "x-requested-with",
    "x-forwarded-for",
    "x-real-ip",
    "x-customheader",
    "user-agent",
    "keep-alive",
    "host",
    "accept",
    "connection",
    "upgrade",
    "content-type",
    "dnt",
    "if-modified-since",
    "cache-control",
    "Accept-Encoding",
    "Accept-Language",
    "User-Agent",
    "Accept",
    "DNT",
    "Connection",
    "Upgrade-Insecure-Requests",
    "Cache-Control",
    "Pragma",
    "Content-Length",
    "Content-Type",
    "Accept-Type"
],
 methods: ["GET", "POST", "PUT"]
})
)
server.use(plugins.fullResponse())

server.get("/api/values", personController.readAll);
server.get("/api/values/:id", personController.readOne);
server.post("/api/values/", personController.createPerson);
server.put("/api/values/", personController.updatePerson);
server.del("/api/values/", personController.delPerson);



server.on('uncaughtException', (req, res, route, err) => {
log.error(err.stack)
res.send(err)
});

server.listen(config.port, function () {

})
我想用这种方式解决这个问题,但如果不行,我可能不得不换回Express

新信息: 现在,当我使用firefox浏览器时,我可以使用完全粗糙。我使用服务器来承载我的节点应用程序。该服务器是一个使用nginx的vmware with ubuntu服务器发行版。但是,当我使用jmeter发布完全相同的请求时,我无法访问完整的crud功能,只能获取。这是fire fox的请求

Host: 192.168.131.128
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101
Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: sv-SE,sv;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0, no-cache
Content-Type: application/json
Content-Length: 174
Pragma: no-cache
看起来不同的请求源以某种方式触发了服务器上不同的CORS设置

使用下面的类

将CORS从“/path/to/CORS.js”导入

新建CORS(服务器)。启用CORSRoutes()


你能把邮寄要求寄出去吗?您是否将
application/json
设置为请求的内容类型?正文分析器不在
中。请使用restify的
。嘿!谢谢你的快速回复。我刚刚将server.use(plugins.fullResponse())改为server.pre(plugins.fullResponse()),它现在至少可以用于同一来源,但不能用于postman。我知道我以前使用过内容类型应用程序,但现在当我添加它时,我使用了请求中的参数!
class CORS {

    constructor(server) {
        this.server = server;
    }

    enableCorsRoutes = () => {
        this.setCorsCredentialHeaders();
        this.getCorsRoutes().forEach((route) => {
            this.server.opts(route, this.enableCors);
        });
    }

    enableCors = (req, res) => {
        const header = req.header('origin');
        if (!this.isOriginAllowed(header)) {
            return res.send(405);
        }
        res.setHeader('Access-Control-Allow-Origin', header);
        res.setHeader('Access-Control-Allow-Headers', this.getAllowedHeaders().join(','));
        res.setHeader('Access-Control-Allow-Methods', this.getAllowedMethods().join(','));
        res.setHeader('Access-Control-Max-Age', this.getCacheTimeForPreflightRequest());
        return res.send(200);
    }

    isOriginAllowed = (origin) => {
        let result = false;
        this.getAllowedOrigins().forEach((allowedOrigin) => {
            if (origin.includes(allowedOrigin)) {
                result = true;
            }
        });
        return result;
    }

    getAllowedHeaders = () => ([
        'cache-control',
        'content-type',
        'x-signature',
        'x-test-mode',
        'x-request-id',
    ])

    getAllowedMethods = () => ([
        'OPTIONS',
        'GET',
        'POST',
        'PUT',
        'DELETE',
        'PATCH',
    ])

    getAllowedOrigins = () => ([
        'example.com',
        'example.org'
    ])

    getCorsRoutes = () => ([
        '/\.*/',
    ])

    getCacheTimeForPreflightRequest = () => {
        return 864000; // ten days in seconds
    }

    setCorsCredentialHeaders = () => {
        this.server.use((req, res, next) => {
            res.once('header', () => {
                let isCorsRoute = false;
                this.getCorsRoutes().forEach((route) => {
                    if (new RegExp(route).test(req.url)) {
                        isCorsRoute = true;
                    }
                });
                if (isCorsRoute && req.header('origin')) {
                    res.setHeader('Access-Control-Allow-Origin', req.header('origin'));
                    res.setHeader('Access-Control-Allow-Credentials', true);
                }
            });
            next();
        });
    }
}

export default CORS;