iT邦幫忙

0

前端使用GraphQL時,遇到 405 (Method Not Allowed)

  • 分享至 

  • xImage

大家好,
我想請問,我的後端架構是 nodejs + graphql。
因為只是在測試中,目前還沒有使用到資料庫。
後端的環境是:

"node": "^12.22.7",
"express": "^4.18.2",
"express-graphql": "^0.12.0",
"graphql": "^15.3.0",

後端測試的code:

const express = require('express');
const { buildSchema } = require('graphql');
const graphqlHTTP = require('express-graphql').graphqlHTTP
const bodyParser = require('body-parser');

const users = [
    {
        id: 1,
        name: 'Fong',
        age: 23
    },
    {
        id: 2,
        name: 'Kevin',
        age: 40
    },
    {
        id: 3,
        name: 'Mary',
        age: 18
    }
];

const Schema = buildSchema(`
    type User{
        id: Int,
        name: String,
        age: Int
    }
    input UserInput{
        name: String,
        age: Int
    }

    type Query{
        users:[User]
    }

    type Mutation{
        create(input:UserInput):User
        update(id:Int!,input:UserInput):User
        delete(id:Int!):Int
    }
`)
const root = {
    users: () => users,
    create: ({ input }) => {
        let lastId = users[users.length - 1]['id']
        let obj = { ...input, id: lastId + 1 }
        users.push(obj)
        return obj
    },
    update: ({ id, input }) => {
        let updatedData = null
        let itemIndex = users.findIndex(item => item['id'] == id)
        if (itemIndex > 0) {
            users[itemIndex] = { ...users[itemIndex], ...input }
            updatedData = { ...users[itemIndex] }
        }
        return updatedData
    },
    delete: ({ id }) => {
        let itemIndex = users.findIndex(item => item['id'] == id)
        if (itemIndex > 0) {
            users.splice(itemIndex, 1)
            return 1
        }
        return 0
    }
}

const app = express();

//這裡,設定了 POST ,前端還是會收到403錯誤
app.use((req, res, next) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
    res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Access-Control-Request-Headers, Access-Control-Request-Method");
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});


app.use('/graphql', bodyParser.json(), graphqlHTTP({
    schema: Schema,
    rootValue: root,
    graphiql: true
}))

app.listen(5500, () => {
    console.log('已連線');
})

前端部分,我直接用 index.html 進行測試

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        let url = 'http://127.0.0.1:5500/graphql'
        let fetchBody = {
            body: JSON.stringify({
                query: `
                    {
                        users{
                            id
                            name
                            age
                        }
                    }
                `
            }),
            headers: {
                'content-type': 'application/json'
            },
            method: 'POST'
        }

        const response = async () =>await fetch(url, fetchBody)
        const list =  response().json()
    </script>
</body>

</html>

不過出現了 Method Not Allowed 的錯誤。

POST http://127.0.0.1:5500/graphql net::ERR_ABORTED 405 (Method Not Allowed)

請問要怎麼修改呢?感謝

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
woeichern
iT邦新手 1 級 ‧ 2022-12-14 14:26:12
最佳解答

有可能前端先發送了 option / head
是這類請求被擋下來了

可參考:https://stackoverflow.com/questions/62637876/graphql-error-method-not-allowed-must-be-one-of-options

greenriver iT邦研究生 4 級 ‧ 2022-12-14 16:47:58 檢舉

謝謝,
後來我加了套件const cors = require('cors')
再把port改成3000,就可以了。
目前猜測是port設定成5500的關係。

greenriver iT邦研究生 4 級 ‧ 2022-12-14 16:49:06 檢舉

前後端用到相同的port

我要發表回答

立即登入回答