【发布时间】:2021-07-12 06:36:18
【问题描述】:
我正在尝试将文件(图像)从我的客户端应用程序(react)发送到服务器(node.js)。
我收到错误消息:TypeError: createReadStream is not a function
这是我的代码:
graphql 架构:
type File {
filename: String!
mimetype: String!
enconding: String!
}
extend type Mutation {
singleUpload(file: Upload!): File!
}
graphql 解析器:
module.exports = {
Mutation: {
async singleUpload(_, { file }) {
try {
const { createReadStream, filename } = await file;
const stream = createReadStream();
const pathName = path.join(__dirname, `/src/image/${filename}`);
await stream.pipe(fs.createWriteStream(pathName));
return file;
} catch (err) {
console.log(err);
return err;
}
},
}
阿波罗服务器:
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context,
introspection: true,
playground: {
settings: {
"schema.polling.enable": false,
"editor.fontSize": 18,
},
},
});
应用客户端
const appClient = new ApolloClient({
link: createUploadLink({ uri: baseURL + "/graphql" }),
cache: new InMemoryCache(),
});
const SINGLE_UPLOAD = gql`
mutation singleUpload($file: Upload!) {
singleUpload(file: $file) {
filename
mimetype
enconding
}
}
`;
const [userImage, setUserImage] = useState();
const handleSubmit = (event: any) => {
uploadFile({ variables: { file: userImage } });
}
在调试服务器中的文件对象时,它看起来像 C://fakeadress/name.jpg
你知道我为什么会收到这个错误吗?
我正在使用所有模块的最新版本。
【问题讨论】:
-
没有发送文件,只有文件名?检查网络请求正文 - 对于上传它应该是表单数据编码,而不是通常的 json 查询+变量
-
感谢您的回答。我认为这就是问题所在......
标签: node.js reactjs graphql fs