FetchError:请求 http://localhost:8080 失败,原因:连接 ECONNREFUSED ::1:8080

问题描述 投票:0回答:0

问题

我正在尝试将我的 Apollo GraphQL 服务器连接到我本地的 SpringBoot RESTFul API:

我的索引文件:

import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'
import typeDefs from './schema.js'
import resolvers from './resolvers.js'
import { MyAPI } from './datasources/api.js'
import { Context } from './interfaces/general'

const server = new ApolloServer<Context>({
    typeDefs,
    resolvers,
    csrfPrevention: false,
});

const { url } = await startStandaloneServer(server, { 
    context: async () => {
        const { cache } = server;
        return {
            dataSources: {
                MyAPI: new myAPI({cache})
            }
        }
    }    
})

console.log(`🚀 Server is running at ${url}`);

我的数据源

import { RESTDataSource, RequestOptions } from "@apollo/datasource-rest"

export class MyAPI extends RESTDataSource {

    override baseURL = 'http://localhost:8080/v1/';
        
    async getHealth(): Promise<string> {
        let data;
        try {
            data = await this.get(`/health`);            
        } catch (error) {
            console.error(`Received an error for health check: ${error}`);
        }
        return data;
    }

    ...

但是,我收到此错误:

FetchError: request to http://localhost:8080/v1/health failed, reason: connect ECONNREFUSED ::1:8080
    at ClientRequest.<anonymous> (/mnt/c/Users/fresh/Documents/React/myproject/graphqlv3/node_modules/node-fetch/lib/index.js:1505:11)
    at ClientRequest.emit (node:events:512:28)
    at Socket.socketErrorListener (node:_http_client:496:9)
    at Socket.emit (node:events:512:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED'

N.B - 我正在使用以下依赖项: "@apollo/datasource-rest": "^5.0.2", "@apollo/server": "^4.4.1", “graphql”:“16.6.0”, 我正在连接到本地 Restful SpringBoot API 服务器。

我试过的

我试过使用不同的程序连接到 API:

  1. Postman - 使用

    localhost:8080/health
    使用 PostMan 连接到 api,成功.

  2. Browser - 在浏览器中运行

    http://localhost:8080/health
    ,这是成功的。

  3. Curl - 运行

    curl http://localhost:8080/health
    成功了。

  4. CORS - 在后端服务器上设置 CORS 标头以允许任何来源。

  5. 代理 - 在我的

    "proxy": "HTTP://localhost:8080"
    文件中添加
    package.json

  6. 使用完全不同的后端服务器和不同的端口。

预期结果

这个请求应该回复:“成功”

javascript node.js reactjs graphql apollo
© www.soinside.com 2019 - 2024. All rights reserved.