大家好,
我想請問,我的後端架構是 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)
請問要怎麼修改呢?感謝
有可能前端先發送了 option
/ head
是這類請求被擋下來了
可參考:https://stackoverflow.com/questions/62637876/graphql-error-method-not-allowed-must-be-one-of-options