gpt4 book ai didi

javascript - 如何为用户制定自定义路线?以及如何为其添加钩子(Hook)?

转载 作者:行者123 更新时间:2023-11-28 17:41:15 25 4
gpt4 key购买 nike

我正在尝试添加路由/me 来获取用户经过身份验证的信息。这就是我的文件里的内容。我尝试在 users.services 文件中添加路由/me,但收到此错误:“错误:MethodNotAllowed:此端点不支持方法 find。”

我想通过用户对象(基于 token )获取对 GET 方法的响应以路由“/me”。

users.service.js

// Initializes the `users` service on path `/users`
const createService = require('feathers-sequelize');
const createModel = require('../../models/users.model');
const hooks = require('./users.hooks');

module.exports = function (app) {
const Model = createModel(app);
const paginate = app.get('paginate');

const options = {
name: 'users',
Model,
paginate
};

// Initialize our service with any options it requires
app.use('/users', createService(options));

app.use('/me', {
get(id, params) {
return Promise.resolve([
{
id: 1,
text: 'Message 1'
}
])
}
})

// Get our initialized service so that we can register hooks and filters
const service = app.service('users');

service.hooks(hooks);
};

users.hooks.js

const { authenticate } = require('@feathersjs/authentication').hooks;

const {
hashPassword, protect
} = require('@feathersjs/authentication-local').hooks;

module.exports = {
before: {
all: [ ],
find: [ authenticate('jwt') ],
get: [],
create: [ hashPassword() ],
update: [ hashPassword() ],
patch: [ hashPassword() ],
remove: []
},

after: {
all: [
// Make sure the password field is never sent to the client
// Always must be the last hook
protect('password')
],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},

error: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
}
};

users.model.js

// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;

module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const users = sequelizeClient.define('users', {

email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},


}, {
hooks: {
beforeCount(options) {
options.raw = true;
}
}
});

users.associate = function (models) { // eslint-disable-line no-unused-vars
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/
};

return users;
};

最佳答案

你做了什么

  app.use('/me', {
get(id, params) {
return Promise.resolve([
{
id: 1,
text: 'Message 1'
}
])
}
})

正在实现 /me/:id 的路由。 find方法是为 /me 的基本路由运行的。

不过,我认为单独的服务并不是真正必要的。一个更简单的解决方案是使用 before all 钩子(Hook),如果您访问 /users/me,它会更改 id:

module.exports = function() {
return async context => {
if(context.id === 'me') {
context.id = context.params.user._id;
}
}
}

关于javascript - 如何为用户制定自定义路线?以及如何为其添加钩子(Hook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com