You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js Express服务器启动失败及AWS S3连接问题求助

问题描述

我正在编写一个可连接AWS S3存储桶的简易Node.js Express服务器,目前无法启动该服务器。首次启动成功后,关闭终端便无法再次启动,也不清楚是否仍有进程在占用对应的8080端口。

我尝试使用以下命令启动服务器:

  • node .
  • node index.js
    但仅会弹出一个终端窗口,且该窗口在一秒左右后消失。我已尝试重启机器,但问题仍未解决。
我的Node.js代码
const app = require('express');
const AWS = require('aws-sdk');
const express = require('express');
const PORT = 8080;

app.request(express.json());

const awsKey = 'randomkey';
AWS.config.update({region: 'eu-west-2'});

const s3 = new AWS.S3();

app.get('/image', (req, res) => {
     let params = {Bucket: 'competitionimagebucket', Key: awsKey};
    s3.getObject(params, (err, data) => {
         console.log(data);
     });
    res.status(200).send({
        "text": 'hello'
    });
});

app.listen(PORT, () => console.log('Server running on Port ' + PORT));
package.json文件
{
  "name": "express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.1457.0",
    "express": "^4.18.2"
  }
}
排查与修复步骤

1. 修复代码中的致命错误

你的代码存在两个直接导致服务器启动即崩溃的错误:

  • Express实例初始化错误:const app = require('express'); 需改为 const app = express(); —— require('express') 返回的是一个函数,必须调用它才能创建Express应用实例。
  • 中间件挂载错误:app.request(express.json()); 是错误写法,正确应为 app.use(express.json()); —— Express通过use方法挂载中间件。

修正后的完整代码:

const express = require('express');
const AWS = require('aws-sdk');
const PORT = 8080;

// 正确初始化Express实例
const app = express();

// 正确挂载JSON解析中间件
app.use(express.json());

const awsKey = 'randomkey';
AWS.config.update({region: 'eu-west-2'});

const s3 = new AWS.S3();

app.get('/image', (req, res) => {
     let params = {Bucket: 'competitionimagebucket', Key: awsKey};
    s3.getObject(params, (err, data) => {
         // 增加错误捕获,避免S3请求出错导致服务器崩溃
         if (err) console.error('S3请求错误:', err);
         else console.log('S3返回数据:', data);
     });
    res.status(200).send({
        "text": 'hello'
    });
});

app.listen(PORT, () => console.log('Server running on Port ' + PORT));

2. 检查并释放端口占用

如果修复代码后仍无法启动,先确认8080端口是否被其他进程占用:

  • Windows系统:打开命令提示符,执行:
    netstat -ano | findstr :8080
    
    找到对应的PID后,执行taskkill /PID <PID> /F强制结束进程。
  • macOS/Linux系统:打开终端,执行:
    lsof -i :8080
    
    找到对应的PID后,执行kill -9 <PID>强制结束进程。

3. 正确启动服务器的方式

不要直接双击脚本启动(崩溃后无法查看错误日志),打开终端进入项目目录,执行:

node index.js

若启动失败,终端会显示具体错误信息,方便进一步排查。

4. 可选:添加便捷启动脚本

在package.json的scripts中添加启动命令,后续启动更方便:

"scripts": {
  "start": "node index.js",
  "test": "echo \"Error: no test specified\" && exit 1"
}

之后只需执行npm start即可启动服务器。

内容的提问来源于stack exchange,提问作者Jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 00:11:28