【问题标题】:express http: 500 error on graphql mutation to create user from apollo client in react表达 http:graphql 突变上的 500 错误以在反应中从阿波罗客户端创建用户
【发布时间】:2021-12-09 07:29:23
【问题描述】:

尝试在 apollo 中使用 graphql 突变添加用户,但我的服务器给了我:Uncaught (in promise) Error: Response not successful: Received status code 500 不确定我是否需要指定服务器以使用 post 路由?我想如果您只是告诉 express 在特定路线(即 /graphql)使用 graphql,它会根据需要读取突变请求

不知道为什么我的服务器会向我发送 500 错误。作为旁注,我可以在我的 react 应用程序中使用 apollo 从我的服务器获取用户而没有问题

希望有人能告诉我我的快递应用程序出了什么问题,这可能会导致我的问题,我已尝试添加一个帖子路线,如您将在示例中看到的,但我仍然收到 500 错误

反应中的阿波罗突变

import {gql} from '@apollo/client';

export const CREATE_CUSTOMER_MUTATION = gql`
mutation addCustomer($id: Int! $name: String! $email: String! $age: Int!){
    addCustomer
    (id: $id name: $name email: $email age: $age)
          {
            id
            name
            email
            age
    }
}

`

添加用户的表单

import React, {useState} from 'react'
import { CREATE_CUSTOMER_MUTATION } from '../GraphQL/Mutations'
import { useMutation } from '@apollo/client';

export default function Form() {
    const [id,setId] = useState("");
    const [name,setName] = useState("");
    const [email,setEmail] = useState("");
    const [age,setAge] = useState("");

    const [addCustomer, {error}] = useMutation(CREATE_CUSTOMER_MUTATION)
    const newCustomer = () =>{
        addCustomer({
            variables: {
                id: id,
                name: name,
                email: email,
                age: age
            }
        })
        if(error){
            console.log(error);
        }
    };

    return (
        <div>
            <input type="text"
             placeholder="id"
             onChange = {(e) =>{
             setId(e.target.value)}}/>

            <input type="text"
             placeholder="name"
             onChange = {(e) =>{
             setName(e.target.value)}}/>

            <input type="text" 
            placeholder="email"
            onChange = {(e) =>{
            setEmail(e.target.value)}}/>

            <input type="text" 
            placeholder="age"
            onChange = {(e) =>{
            setAge(e.target.value)}}/>
            <button onClick={addCustomer}>Create Customer</button>
            
        </div>
    )
}


快速服务器

const express = require('express')
const expressGraphQL = require('express-graphql').graphqlHTTP
const schema = require('./schema.js')
const cors = require('cors')
const port = process.env.PORT || 3000


const app = express();
//allow CORS
app.use(cors())


app.use('/graphql', expressGraphQL({
    schema:schema,
    graphiql:true,
}));


app.get('/', (req, res) => {
    res.send('Hello World!')
  })


app.listen(port, ()=>{
 console.log(`server is running on port ${port}`)
});

我的 express 服务器上的我的 graphql 架构

const axios = require('axios')
const {
    GraphQLObjectType,
    GraphQLString,
    GraphQLInt,
    GraphQLSchema,
    GraphQLList,
    GraphQLNonNull
 } = require('graphql')


//hardcoded data

const customers =[
    {id: 1, name: 'luther wardle', email: 'lwardle@mail.com', age:35},
    {id: 2, name: 'steve smith', email: 'ssmith@mail.com', age:30},
    {id: 3, name: 'the main mayne', email: 'itme@mail.com', age:29},
    {id: 4, name: 'jojo mojo', email: 'jmojo@mail.com', age:14}   
]


//customer type
const CustomerType = new GraphQLObjectType({
    name: 'Customer',
    fields: () =>({
        id: {type:GraphQLString},
        name: {type:GraphQLString},
        email: {type:GraphQLString},
        age: {type: GraphQLInt}
    })
})

//Root Query
const RootQuery = new GraphQLObjectType({
    name: 'RootQueryType',
    fields:{
        customer: {
            type:CustomerType,
            args:{
                id: {type:GraphQLString}
            },
            resolve(parentValue,args){
               
                for(let i =0; i<customers.length; i++){
                    if(customers[i].id == args.id){
                        return  customers[i]
                    }
                }
           
              
            }
        },

        customers:{
            type: new GraphQLList(CustomerType),
                resolve(parentValue,args){
                   
                    return customers
                }   
        }
    }
    
});
//mutation
const mutation = new GraphQLObjectType({
    name: 'mutation',
    fields:{
        addCustomer:{
            type:CustomerType,
            args:{
                id: {type: new GraphQLNonNull(GraphQLInt)},
                name: {type: new GraphQLNonNull(GraphQLString)},
                email: {type: new GraphQLNonNull(GraphQLString)},
                age: {type: new GraphQLNonNull(GraphQLInt)}
                
            },
            resolve(parentValue,args){
              
                // add to the list
              return customers
            }
        },
        deleteCustomer:{
            type:CustomerType,
            args:{
                id:{type: new GraphQLNonNull(GraphQLString)}
            },
            resolve(parentValue,args){
                return axios.delete('http://localhost:3000/customers/'+args.id)
                .then(res => res.data);
            }
        },
        editCustomer:{
            type:CustomerType,
            args:{
                id:{type: new GraphQLNonNull(GraphQLString)},
                name:{type: GraphQLString},
                email:{type:GraphQLString},
                age:{type: GraphQLString}
            },
            resolve(parentValue,args){
                return axios.patch('http://localhost:3000/customers/'+args.id,args)
                .then(res => res.data);
            }
        }
    }
})

module.exports = new GraphQLSchema({
    query: RootQuery,
    mutation
});

【问题讨论】:

  • 您能否在此处包含有关您实际遇到的错误的任何信息?旁注,您不需要 POST 路线。 app.use 会为您做到这一点。
  • 我做了一些编辑,因为我意识到我没有将 ID 指定为变量,但我使用的是硬编码数据,所以没有任何东西为我处理 ID...我也发布了我得到的错误并删除了发布路线,我得到的唯一信息是回复很糟糕Uncaught (in promise) Error: Response not successful: Received status code 500 抱歉,如果这不是很有帮助 XD 我知道这种感觉
  • 我会说我没有问题让所有客户从服务器返回,只是突变导致了这个问题,这让我相信我的查询是问题,但对我来说看起来很好
  • 您已启用 GraphiQL。能否直接对 API 进行查询并获得更好的错误堆栈?
  • 感谢您的提示,经过一番研究后,我发现当 ID 和 Age 应该是 Ints 时,我的表单将所有变量作为字符串传递,在解析 Ints 后问题得到解决:)跨度>

标签: node.js reactjs express graphql apollo


【解决方案1】:

当 ID 和 Age 应该是 Ints 时,我的表单将所有变量作为字符串传递,解析 Ints 后问题已解决

如下所示,我更改了表单组件中的变量


    const newCustomer = () =>{
        addCustomer({
            variables: {
                id: parseInt(id),
                name: name,
                email: email,
                age: parseInt(age)
            }
        })
        if(error){
            console.log(error);
        }
    };

  

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2021-07-13
    • 2021-04-03
    • 2018-01-13
    • 2021-01-19
    • 2018-04-13
    • 2019-02-09
    • 2019-01-13
    • 2021-06-28
    相关资源
    最近更新 更多