[英]How do I pass in objectId from the react front end to server-side graphql?
So I am trying to call a graphql mutation with the useMutation hook and it is supposed to store a new record with a objectId reference to another collection in my mongodb.所以我试图用 useMutation 挂钩调用 graphql 突变,它应该存储一条新记录,其中 objectId 引用到我的 mongodb 中的另一个集合。
const handleSubmit = async (e) => {
e.preventDefault();
const ticket = {
ticketOwner: "60bd776e3e088a27ecae9dbb",
venue: "Chase Center"
};
console.log(ticket);
try {
await createTicket({variables: {ticket}});
} catch (e) {
console.log(e);
}
handleClose();
}
the mutation is this snippet below and I have tested it on the playground to verify the server-side code is setup and running properly.突变是下面的这个片段,我已经在操场上对其进行了测试,以验证服务器端代码是否已正确设置和运行。
export const CREATE_TICKET = gql`
mutation ($ticketOwner: ID!, $venue: String!) {
createTicket(ticketOwner: $ticketOwner, venue: $venue) {
_id
venue}}`;
Everytime I execute the handlesubmit (button event handler) with my react front-end, I keep getting a 400 http://localhost:3000/graphql 400 (Bad Request)
so I figured it might have to do with how I am passing in the id reference for the referenced collection.每次我用我的反应前端执行 handlesubmit(按钮事件处理程序)时,我不断收到 400
http://localhost:3000/graphql 400 (Bad Request)
所以我认为这可能与我传递的方式有关引用集合的 ID 引用。 Does anyone have a better approach on how it should be handled from the front end?有没有人对如何从前端处理它有更好的方法? (Im aware its hardcoded for now for testing purposes.)
(我知道现在出于测试目的对其进行了硬编码。)
Check.network tab to see the contents of the error.检查.network 选项卡以查看错误内容。 Also see if you have trailing forward slash in Apollo Client
createHttpLink
URI parameter.另请查看 Apollo Client
createHttpLink
URI 参数中是否有尾部正斜杠。
It should be like this应该是这样的
const httpLink = createHttpLink({
uri: "http://localhost:5000/graphql",
});
Lastly you might need cors
in place on the backend, but firstly check.network tab to see what you're getting from server最后,您可能需要在后端放置
cors
,但首先检查网络选项卡以查看您从服务器获得的内容
The mutation expects two variables named ticketOwner
and venue
.突变需要两个名为
ticketOwner
和venue
的变量。
mutation ($ticketOwner: ID!, $venue: String!)
While the variable passed is only ticket
.而传递的变量只是
ticket
。
await createTicket({variables: {ticket}});
To fix, properly pass the variables based on what the mutation expects.要修复,请根据突变的预期正确传递变量。
await createTicket({
variables: {
ticketOwner: ticket.ticketOwner,
venue: ticket.venue
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.