搭建自定义URL短链API时遇localhost连接拒绝问题求助
问题解决指南:URL短链服务连接错误与REST客户端替代方案
一、修复Connection refused错误
你的核心问题出在**routes/url.js文件内容完全错误**——当前文件里放的是package.json的重复内容,而非Express路由逻辑,导致Express无法识别/api/url/shorten接口,甚至服务器启动时就会报错,最终引发连接拒绝。
步骤1:修正routes/url.js
把routes/url.js的全部内容替换为以下完整路由代码(实现短链生成核心功能):
const express = require('express'); const router = express.Router(); const validUrl = require('valid-url'); const shortid = require('shortid'); const config = require('config'); const Url = require('../models/Url'); // 生成短链接口 router.post('/shorten', async (req, res) => { const { longUrl } = req.body; const baseUrl = config.get('baseUrl'); // 验证基础域名有效性 if (!validUrl.isUri(baseUrl)) { return res.status(401).json('无效的基础URL'); } // 生成唯一短链码 const urlCode = shortid.generate(); // 验证传入的长URL有效性 if (validUrl.isUri(longUrl)) { try { let url = await Url.findOne({ longUrl }); // 长URL已存在,直接返回已有短链 if (url) { res.json(url); } else { // 拼接完整短链地址 const shortUrl = baseUrl + '/' + urlCode; // 创建新的URL记录并保存到MongoDB url = new Url({ longUrl, shortUrl, urlCode, date: new Date() }); await url.save(); res.json(url); } } catch (err) { console.error(err); res.status(500).json('服务器内部错误'); } } else { res.status(401).json('无效的长URL'); } }); module.exports = router;
步骤2:确保服务器正常启动
- 安装依赖:在项目根目录执行
npm install - 启动开发服务器:执行
npm run dev - 检查控制台输出:必须同时出现
Server running on port 5000和MongoDB Connected...- 如果没出现MongoDB连接提示:检查
config/default.json里的mongoURI是否替换了密码(把<apishort>换成你的MongoDB Atlas真实密码),同时确认Atlas控制台的Network Access已添加当前IP地址 - 如果服务器启动报错:检查代码拼写错误,比如
index.js里的express.json({ extented: false})应该是extended(拼写错误,不过不影响启动,但建议修正)
- 如果没出现MongoDB连接提示:检查
步骤3:重新发送请求
服务器正常启动后,再发送POST请求即可正常访问接口。
二、IntelliJ中REST Client插件替代方案
如果RESTClient插件版本不兼容,可用以下几种替代方式:
1. 用IntelliJ内置HTTP Client
JetBrains全家桶(包括IntelliJ)自带HTTP Client,无需额外插件:
- 右键点击
api.http文件,选择Run 'POST...'即可发送请求 - 若文件显示红色,检查语法:确保
Content-Type和JSON之间空一行,且JSON缩进正确,示例:POST http://localhost:5000/api/url/shorten Content-Type: application/json { "longUrl": "https://stackoverflow.com/questions/48419801/org-apache-http-conn-httphostconnectexception-connect-to-localhost19538-local" }
2. 使用Postman
下载Postman客户端,新建POST请求:
- 填入URL:
http://localhost:5000/api/url/shorten - 切换到Body标签,选择
raw->JSON格式,粘贴请求体后发送
3. 使用curl命令
在终端直接执行:
curl -X POST -H "Content-Type: application/json" -d '{"longUrl":"https://stackoverflow.com/questions/48419801/org-apache-http-conn-httphostconnectexception-connect-to-localhost19538-local"}' http://localhost:5000/api/url/shorten
内容的提问来源于stack exchange,提问作者Danka
相关产品推荐
相关产品推荐

