我有一个带有预定义http请求的数据库服务器(使用orientdb)
我想以下列形状和形式写一个帖子请求
http://localhost:2480/database/demo/plocal
数据库名称(demo)将来自html中的表单,我必须在请求中使用基本身份验证才能进行身份验证和创建数据库。
我正在使用node.js和express来创建这个api,我的帖子请求的代码形式应包含所有这些信息。
到目前为止,我已经创建了以下路线,但我对如何创建此帖子请求感到很遗憾:
// Create DB
app.get('/createdb', (req, res) => {
res.render('createdb');
});
app.post('/createdb', (req, res) => {
// http://localhost:2480/database/demo/plocal
const serverString = 'http://localhost:2480/database/';
const dbName = req.body.dbname;
const dbType = '/plocal';
console.log(serverString + dbName + dbType);
res.send('createdb page');
});
在我的console.log中我可以从我的表单中看到db名称。 提前致谢
答案 0 :(得分:0)
要进行API调用,请使用PostMan。
对于身份验证,您可以使用令牌或会话。我个人使用npm express-session
在app.js中设置会话
var session = require('express-session');
app.use(session({
secret: '2C44-1T58-WFpQ350',
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 3600000 * 2
}
}));
登录方式
router.post('/login', async function (req, res, next) {
//Run DB query check
try {
//Call db check if user is in user Table if yes set session
var result = await qp.executeAndFetchPromise('select * from user where email = ? AND ava_status = 1', [req.body.email], dbconfig);
if (result.length == 1) {
//encryption to be added later
if (result[0].password == req.body.password) {
//set session
req.session.userid = result[0].id;
req.session.name = result[0].name;
req.session.role = result[0].role;
req.session.group_id = result[0].group_id;
req.session.userinfo = result[0];
// res.render('index' , user = result[0])
res.redirect('/dashboard');
}
} else {
throw (new Error());
}
}
catch (error) {
res.render('login', feedback = { "message": "Invalid username/password" });
}
});
在App中,js
var debugging = false; //IMPORTANT
var API = false;
function authChecker(req, res, next) {
if (API == false) {
let userRoles = custom.getAllRoles();
let temp = arrayFindIndex(userRoles, x => x == req.session.role );
if (temp != -1 ) {
next();
} else {
if (debugging) {
if (!req.session.role && !req.session.role) {
req.session.role = 'ADMIN';
req.session.userid = 1;
req.session.name = "Marcia test Debugging"
}
next();
} else {
// var err = new Error('Session timeout, Please login again');
// err.status = 502;
// next(err);
res.redirect('/login');
}
}
}
}
在路由上运行authCehcker方法需要身份验证
//Setting web routes
app.use('/', indexRouter); // public can access
//Routes under will be checked
app.use(authChecker); //routes under this method will be checked by the authChecker method
app.use('/users', usersRouter);
app.use('/dashboard', dashboard);
app.use('/brand', brand);
答案 1 :(得分:0)
您可以使用curl:curl -X POST -h 'authorization: <basic auth here>' http://localhost:2480/database/demo/plocal