【发布时间】:2020-09-01 17:45:17
【问题描述】:
当通过 axios 发送图像时,我发现我必须使用 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?
},
}
前端:
我这样构建请求:
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('0', 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,
// headers: obj.headers,
},
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 将如何到达我的解析器端点,因此我在后端返回后做错了什么:
(node:748) UnhandledPromiseRejectionWarning: [object Array] (node:748) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这 错误源于在异步函数内部抛出 没有 catch 块,或拒绝未处理的承诺 使用 .catch()。 (拒绝 ID:1)(节点:748)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。在 未来,未处理的承诺拒绝将终止 具有非零退出代码的 Node.js 进程。
我意识到这很多,但我在这里的 vits 结束时,一整天都在这。任何帮助都深表感谢。
编辑:
由于我的后端受到质疑,我想我只是表明,在发送数据而不像上面那样附加 Formdata 的情况下,我可以让它工作:
const submitForm: SubmitForm = (obj: SendObject) => {
callAxiosFn(
{
method,
url: 'http://localhost:4000/api',
data: obj.data,
},
qlType.toString()
);
};
obj.data 是:
{query: "mutation ($firstName: String!, $email: String!, $l… Age: $age, JobTitle: $jobTitle, File: $file})↵}↵", variables: {…}}
query: "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})↵}↵"
variables:
age: "1977-04-04"
email: "JhoneDoe@hotmail.com"
file: File {name: "something.jpg", lastModified: 1589557760497, lastModifiedDate: Fri May 15 2020 17:49:20 GMT+0200 (centraleuropeisk sommartid), webkitRelativePath: "", size: 32355, …}
firstName: "Jhon"
jobTitle: "SomethingCool"
lastName: "Doe"
password: "CoolPassword!"123"
__proto__: Object
__proto__: Object
在浏览器中发送查询:
编辑:
最近发现我的 fastify 后端可能有读取 formData 的问题。 尝试安装
fastify-multipart
但注册时出错:
FST_ERR_CTP_ALREADY_PRESENT(contentType) ^ FastifyError [FST_ERR_CTP_ALREADY_PRESENT]:
之后我尝试了:
npm uninstall fastify-file-upload
错误仍然存在。
【问题讨论】:
-
错误的变异语法 - 没有返回内容 def - 你必须返回一些东西 - 至少有一些
{ id } -
file不是null-ed -
Fdata.append('file'...- 为什么不是“0”? ....恕我直言,您应该将问题分开...获取有效的客户端配方(第一个链接)并使后端正常工作...然后使用所需的自定义重新创建它...一次更改太多 -
更新了问题以在我不将数据作为 formData 发送时显示功能齐全的后端。那么问题是我没有点击解析器并且文件也不包括在内。
-
mutation name( input ) { result }- 您的查询中有 no result part(我不关心代码).....从 workimg formData (FE ) 示例 并证明 BE 正在工作......然后根据您的需求调整 FE
标签: node.js graphql axios apollo-server fastify