【发布时间】:2021-09-09 17:56:57
【问题描述】:
我正在尝试使用 apollo-angular 从 Angular 将文件上传到 apollo 服务器,但文档令人困惑,而且我在属中找到的信息未更新到最新版本的 apollo angular 和 apollo 服务器。
在前端我有:
变异
export const Save_UserMutation = gql`
mutation SaveUserMutation ($data: UsersInput!, $file: Upload) {
createUser(data: $data, file: $file) {
user
}
}
`
服务
save(_userData: User, emitMessage?: boolean) {
let file = _userData.profilePicture
_userData.profilePicture = (_userData.profilePicture as File).name
const saveUser$ = this.apollo.mutate({
mutation: Save_UserMutation,
variables: {
data: _dataUsuario,
file
},
context: {
useMultipart: true
}
}).subscribe()
}
在后台:
服务器
const server = new ApolloServer({
schema,
context: createContext,
uploads: false
})
上传设置为 false 就像文档所说的 https://www.apollographql.com/docs/apollo-server/data/file-uploads/#gatsby-focus-wrapper
使用 nexus 编写的变异
export const UsersMutation = extendType({
type: 'Mutation',
definition(t) {
t.nonNull.field('createUser', {
type: 'Users',
args: {
data: nonNull(arg({ type: 'UsersInput' })),
file: arg({
type: GraphQLUpload
})
},
async resolve(parent, args, ctx) {
if (args.file) {
const { createReadStream, filename, mimetype, encoding } = await args.file
const stream = createReadStream()
const pathName = path.join(__dirname, 'public', 'profilePictures') + `/${filename}`
await stream.pipe(fs.createWriteStream(pathName))
args.data.profilePicture == pathName
}
args.data.password = await bcrypt.hash(args.data.password, 10)
return ctx.prisma.users.create({
data: args.data
})
}
}),
})
当我尝试上传文件时,出现以下错误。
POST body missing. Did you forget use body-parser middleware?
【问题讨论】:
-
谢谢。但它没有用。它没有解释如何在 apollo 服务器中上传文件。
-
首先,检查您的客户端请求是否符合规范...服务器可以使用其他客户端进行测试,例如Postman, Insomnia ... 关于服务器的许多答案(node14 问题)
标签: angular graphql nexus apollo-server apollo-angular