如何使用参数向静态资源发出请求?

时间:2018-12-21 10:36:29

标签: javascript node.js restify staticresource

我有我的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请求。

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

1 个答案:

答案 0 :(得分: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'
}));