【问题标题】:How to make request to static resource with parameters?如何使用参数向静态资源发出请求?
【发布时间】:2019-05-21 20:03:44
【问题描述】:

我有我的 node.js restify 服务器和带有静态资源的文件夹

const restify = require('restify')

let server = restify.createServer()

server.listen(8080, function () {
    console.log('%s listening at %s', server.name, server.url)
});


server.get('/*', restify.plugins.serveStatic({
        directory: __dirname + '/static',
        default: 'index.html'
    }));

我正在尝试了解如何使用 localhost:8080/index.html?token=123 等参数向 index.html 发出 get 请求

如果token有效,则返回index.html给客户端,否则返回错误

【问题讨论】:

标签: javascript node.js restify staticresource


【解决方案1】:

您可以链接多个请求处理程序和next() 方法 - 首先进行一些参数的验证,然后作为第二个处理程序,使用serveStatic 方法。这是一个例子:

const restify = require('restify')

let server = restify.createServer()

server.listen(8080, function () {
    console.log('%s listening at %s', server.name, server.url)
});


server.get('/*', (request, response, next) => {
    const token = request.query.token;
    if(token !== '123') {
        //those two lines below will stop your chain and just return 400 HTTP code with some message in JSON
        response.send(400, {message: "Wrong token"});
        next(false); 
        return;
    }
    next(); //this will jump to the second handler and serve your static file
    return;
},
restify.plugins.serveStatic({
    directory: __dirname + '/static',
    default: 'index.html'
}));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多