javascript - 出现 405 错误,Node Js - 找不到方法

标签 javascript node.js http-headers xmlhttprequest graphql-js

我正在尝试在 Node js 中运行服务器,它实际上是一个 GraphQL 服务器。我只是从 React JS 的客户端调用该方法

客户端在 localhost:3000 中运行,服务器端在 localhost:4000

客户端代码

var dice = 3;
var sides = 6;
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open("POST", "http://localhost:4000/graphql");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.onload = function () {
    debugger;
  console.log('data returned:', xhr.response);
}
var query = `query RollDice($dice: Int!, $sides: Int) {
  rollDice(numDice: $dice, numSides: $sides)
}`;
xhr.send(JSON.stringify({
  query: query,
  variables: { dice: dice, sides: sides },
}));

在服务器端,我使用以下代码

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    rollDice(numDice: Int!, numSides: Int): [Int]
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  rollDice: function ({numDice, numSides}) {
    var output = [];
    for (var i = 0; i < numDice; i++) {
      output.push(1 + (numSides *3));
    }
    return output;
  }
};

var app = express();
//CORS middleware
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

我收到的错误是

XMLHttpRequest 无法加载 http://localhost:4000/graphql 。预检响应具有无效的 HTTP 状态代码 405

我有什么遗漏的吗...

谢谢。

最佳答案

您需要通过正确响应 OPTIONS 请求来处理 CORS 代码中的飞行前请求 (OPTIONS):

function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware

    if (req.method === "OPTIONS") {
        return res.status(200).end();
    }

    return next();
}

关于javascript - 出现 405 错误,Node Js - 找不到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107002/

相关文章:

javascript - 加载共享库时出错 : libgtk-3. so.0: 无法打开共享对象文件: 没有这样的文件或目录

javascript - 发送后 Node 抛出新错误 ('Can\' t 设置 header 。')

node.js - Mongoose 插件将额外数据分配给字段但不保存到数据库

java - 如何使用 java 发送带有用户名和密码的 SOAP 请求,就像在 SOAP UI 中一样

java - request-filter-servlet-jsp 链中的响应

javascript - 如何仅在加载 Google Maps API 时加载 jquery 插件?

javascript - Three.js - 在缩放时保持对象静态

javascript - 我该如何解决 Uncaught TypeError : Cannot read property 'top' of undefined

javascript - 在 jekyll 中可以进行 JS 缩小吗?

javascript - 在 NodeJS 中根据内容长度查找视频时长