【发布时间】:2018-08-10 05:31:23
【问题描述】:
我现在正在试用 Prisma 和 React Native。目前我正在尝试使用包 _apollo-upload-client (https://github.com/jaydenseric/apollo-upload-client) 将图像上传到我的数据库。但这并不顺利。
目前我可以从 Expo 中选择带有ImagePicker 的图像。然后我尝试使用 Apollo 客户端进行突变:
await this.props.mutate({
variables: {
name,
description,
price,
image,
},
});
但我收到以下错误:
Network error: JSON Parse error: Unexpected identifier "POST"
- node_modules/apollo-client/bundle.umd.js:76:32 in ApolloError
- node_modules/apollo-client/bundle.umd.js:797:43 in error
而且我相信它来自这些代码行:
const image = new ReactNativeFile({
uri: imageUrl,
type: 'image/png',
name: 'i-am-a-name',
});
这与他们的示例几乎相同,https://github.com/jaydenseric/apollo-upload-client#react-native。
imageUrl 来自我的州。当我 console.log image 我得到以下信息:
ReactNativeFile {
"name": "i-am-a-name",
"type": "image/png",
"uri": "file:///Users/martinnord/Library/Developer/CoreSimulator/Devices/4C297288-A876-4159-9CD7-41D75303D07F/data/Containers/Data/Application/8E899238-DE52-47BF-99E2-583717740E40/Library/Caches/ExponentExperienceData/%2540anonymous%252Fecommerce-app-e5eacce4-b22c-4ab9-9151-55cd82ba58bf/ImagePicker/771798A4-84F1-4130-AB37-9F382546AE47.png",
}
所以有些东西突然出现了。但我不能再进一步了,我希望我能从某人那里得到一些提示。
我也没有包含来自后端的任何代码,因为我认为问题出在前端。 但是如果有人想看看后端,我可以更新问题,或者你可以看看这里:https://github.com/Martinnord/Ecommerce-server/tree/image_uploads。
非常感谢您的阅读!干杯。
更新
在有人询问服务器中的逻辑后,我决定将其粘贴在下面:
Product.ts
// import shortid from 'shortid'
import { createWriteStream } from 'fs'
import { getUserId, Context } from '../../utils'
const storeUpload = async ({ stream, filename }): Promise<any> => {
// const path = `images/${shortid.generate()}`
const path = `images/test`
return new Promise((resolve, reject) =>
stream
.pipe(createWriteStream(path))
.on('finish', () => resolve({ path }))
.on('error', reject),
)
}
const processUpload = async upload => {
const { stream, filename, mimetype, encoding } = await upload
const { path } = await storeUpload({ stream, filename })
return path
}
export const product = {
async createProduct(parent, { name, description, price, image }, ctx: Context, info) {
// const userId = getUserId(ctx)
const userId = 1;
console.log(image);
const imageUrl = await processUpload(image);
console.log(imageUrl);
return ctx.db.mutation.createProduct(
{
data: {
name,
description,
price,
imageUrl,
seller: {
connect: { id: userId },
},
},
},
info
)
},
}
【问题讨论】:
-
您的服务器中的文件上传逻辑在哪里?我找不到它。
-
@marktani 我已经更新了这个问题。感谢您的提问。
-
另外,服务器端的大部分代码都来自
graphql-yogas示例。 github.com/graphcool/graphql-yoga/blob/master/examples/…
标签: react-native graphql apollo prisma