【问题标题】:Cannot GET / error using express无法使用 express 获取 / 错误
【发布时间】:2018-01-19 09:21:53
【问题描述】:

我是 nodeJS 的新手,我正在尝试关注这个tutorial。

我的代码:

// server/index.js
import express from 'express';
import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import bodyParser from 'body-parser';
import { createServer } from 'http';
import { Schema } from './data/schema';
import { Mocks } from './data/mocks';
const GRAPHQL_PORT = 8000;
const app = express();
const executableSchema = makeExecutableSchema({
  typeDefs: Schema,
});
addMockFunctionsToSchema({
  schema: executableSchema,
  mocks: Mocks,
  preserveResolvers: true,
});
// `context` must be an object and can't be undefined when using connectors
app.use('/graphql', bodyParser.json(), graphqlExpress({
  schema: executableSchema,
  context: {}, // at least(!) an empty object
}));
app.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
}));
const graphQLServer = createServer(app);
graphQLServer.listen(GRAPHQL_PORT, () => console.log(`GraphQL Server is now running on http://localhost:${GRAPHQL_PORT}/graphql`));

报错Cannot GET /

我了解到createServer 函数可能已被弃用,但我不知道如何修复它。

【问题讨论】:

  • 您在哪里看到此错误?如果您要去http://localhost:8000/ 并在浏览器中看到它,那么这是预期的行为——您只为/graphql 和/graphiql 定义了路由,而不是/。
  • 需要详细说明吗?

标签: node.js express graphql


【解决方案1】:

使用app.listen(port, function(){console.log('server started')}); 代替 createServer(app)。

【讨论】:

  • 那你的问题完全出在我没用过的graphql上。您的快速应用程序上没有为 / 注册任何路线
【解决方案2】:

当您使用 express 时,您必须明确定义应用程序使用的路由。例如,如果您使用app.get('/hello', handler) 定义路由,那么对localhost/hello 的任何GET 请求都将路由 到该处理程序。然后它可以执行任何逻辑并返回响应,例如 JSON 对象、网页等。

Express 只会处理您以这种方式定义的路线。因此,如果您只为 GET /hello 的请求定义了一个路由,它将不知道如何 GET /foo,或 GET 您的根路径 /。如果您想实现一种 POST 或 PUT 到 /hello 的方法,那也需要使用不同的路由。

您可以以类似的方式使用app.use 在您的应用程序中实现中间件。虽然中间件通常会接受您的请求,对其进行操作并传递它,但它也可用于分解您的路由逻辑。

对于 GraphQL,请求通常使用 POST 方法发出,但规范确实允许 POST 和 GET 请求。为此,我们必须为app.get('/graphql') 和app.post('/graphql') 定义处理程序。您正在导入和使用的 graphqlExpress 中间件可以方便地为您完成这项工作。

因此,通过您的设置,您已经创建了一些允许您向localhost:8000/graphql 发布和获取的路由。您还在 localhost:8000/graphiql 上启用了 GraphiQL。如果您在启动服务器时在控制台中没有看到任何错误,您应该能够导航到localhost:8000/graphiql 的 GraphiQL 页面并使用您的架构。

但这些是您在服务器上设置的唯一路线。如果您尝试导航到其他任何地方,例如 localhost:8000/ 的根目录,express 将不知道如何处理请求,您将看到您报告的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 2019-10-01
    • 2020-09-06
    • 2021-08-15
    相关资源
    最近更新 更多