如何使用axios将图像上传到graphql后端?"/>
如何使用axios将图像上传到graphql后端?
通过axios发送图像时,我发现必须使用formdata。我在此处添加图像,但是在发送formdata时,我的整个后端都冻结了,只是说“待定”。
已经关注this
以及到目前为止我的尝试:
后端:
阿波罗:
import { ApolloServer, makeExecutableSchema } from 'apollo-server-fastify';
const schema = makeExecutableSchema({ typeDefs, resolvers });
const apolloServer = new ApolloServer({
schema,
uploads: {
maxFileSize: 10000000,
maxFiles: 5,
},
});
(async function() {
app.register(apolloServer.createHandler({ path: '/api' }));
})();
模式:
scalar DateTime
scalar Upload
input addUser {
Email: String!
Password: String
FirstName: String!
LastName: String!
Age: DateTime!
JobTitle: String!
File: Upload
}
type Mutation {
register(input: addUser!): Boolean
}
解析器:
Mutation: {
register: async (obj, args, context, info) => {
// how to get the formData?
},
}
FrontEnd:
我建立这样的请求:
const getMutation = (mutate: MutationNames, returParams?: any): any => {
const mutation = {
login: print(
gql`
mutation($email: String!, $password: String!) {
login(email: $email, password: $password) {
token
refreshToken
}
}
`
),
register: print(
gql`
mutation(
$firstName: String!
$email: String!
$lastName: String!
$age: DateTime!
$jobTitle: String!
$file: Upload
) {
register(
input: {
FirstName: $firstName
LastName: $lastName
Email: $email
Age: $age
JobTitle: $jobTitle
File: $file
}
)
}
`
),
}[mutate];
if (!mutation) return {};
return mutation;
};
在这种情况下,我使用寄存器突变。
我对如何处理数据提取有一些了解,因此我不打算包含它,因为它包含很多代码。数据是在前端正确提取的,并且在发布到后端之前将所有内容都放入formData对象:
const submitForm: SubmitForm = (obj: SendObject) => {
const Fdata = new FormData();
Fdata.append('file', fileImp.file);
Fdata.append('operations', JSON.stringify(obj.data));
const map = {
'0': ['variables.file'],
};
Fdata.append('map', JSON.stringify(map));
callAxiosFn(
{
method,
url: 'http://localhost:4000/api',
data: Fdata,
},
qlType.toString()
);
};
被这样称呼:
const response = await axios({
headers: {
Accept: 'application/json',
'x-token': localStorage.getItem('token'),
'x-refresh-token': localStorage.getItem('refreshToken'),
...(config.headers || {}),
},
...config,
});
配置为AxiosRequestConfig
我发送的内容:
我不完全了解formdata将如何影响我的解析器endpint,因此由于后端返回,我做错了什么:
((node:748)UnhandledPromiseRejectionWarning:[对象数组](node:748)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个由抛出异步函数引起的错误没有障碍,或者拒绝了没有处理的承诺使用.catch()。 (拒绝ID:1)(节点:748)[DEP0018]DeprecationWarning:已弃用未处理的承诺拒绝。在未来,未处理的承诺拒绝将终止具有非零退出代码的Node.js进程。
我意识到这很多,但是我在这里结束了我的工作,整整一天都在这里。任何帮助深表感谢。
回答如下:嗯,我还没有探讨这个话题。但是我知道带有[[GraphQL的axios确实不能很好地工作。 Axios主要用于REST API调用。但是,我非常喜欢这个频道Ben Awad,并从中学到了很多东西。这个家伙真是太棒了,他说的东西很清楚很友善。但是最重要的是,他是GraphQL的狂热者,并通过React.js,TypeORM和PostgreSQL探索并提出了各种主题。以下是他频道中的一些有用链接,它们可能会对您的问题有所帮助:
- Upload Files in GraphQL Using Apollo Upload
- How to Upload a File to Apollo Server in React
更多推荐
如何使用axios将图像上传到graphql后端?
发布评论