Я бы порекомендовал использовать библиотеку для анализа результата, вот полный пример с комментариями, поясняющими детали. Как указал @ Hereti c Monkey, токен находится в объекте запроса, но я бы использовал другой подход.
// this is standard set of imports in app generated by
// express --no-view
// from package npm i -g express-generator
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// token 'parsing' library
var bearer = require('express-bearer-token');
// more boilerplate
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// look for the key in headers: { Authorization: AccessKey <your key> }
// this library also has options for query, body, etc...
// https://www.npmjs.com/package/express-bearer-token
app.use(bearer({ headerKey: 'AccessKey' }));
// if present and what you wanted, proceed, else, fail
var protect = (req, res, next) => (
(req.token && req.token === '12345')
? next()
: next(new Error('bad token'))
);
// example protected (can protect a whole router with router.use(protect))
app.get('/protected', protect, (r, s) => s.json({ data: 'api' }));
// example not protected
app.get('/example', (r, s) => s.json({ not: 'protected' }));
// make sure to status 500 to make axios client throw
app.use((error, r, s, n) => s
.status(500)
.json({ error: (error + '') }));
// run the server
var server = app.listen(3000);
// client code (axios works in browser same exact api)
var axios = require('axios');
// wait until server started
setTimeout(async function() {
// you will get status 500 without key on protected route
try {
await axios.get('http://localhost:3000/protected');
console.log('nope, wont see me print')
} catch (e) {
console.log('error for protected no token:', e.response.data.error);
}
// non protected works as expected
var example = await axios.get('http://localhost:3000/example');
console.log('got example data fine: ', example.data);
// for protected, need to supply header
var protected = await axios({
method: 'get',
url: 'http://localhost:3000/protected',
headers: { Authorization: 'AccessKey 12345' }
});
console.log('got protected data fine w/tok: ', protected.data);
// wait for server to shut down then exit the program
server.close(() => console.log('bye'))
}, 500);