我开始了我在 IT 世界的旅程,从自定义 Url Shortner 服务构建 API 并使用 mongodb Atlas。
我一直在学习本教程以了解更多信息,但每次我发送请求时都会收到此错误:
'POST http://localhost:5000/api/url/shorten
org.apache.http.conn.HttpHostConnectException:连接到本地主机:5000 [localhost/127.0.0.1] 失败:连接被拒绝:连接'
这里是这样的:
index.js
const express = require('express');
const connectDB = require('./config/db');
const app = express();
// Connect to database
connectDB();
app.use(express.json({ extented: false}));
// Define Routes
app.use('/', require('./routes/index'));
app.use('/api/url', require('./routes/url'));
const PORT = 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
`
package.json
{
"name": "url_shortner_service",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"config": "^3.3.9",
"express": "^4.18.2",
"mongoose": "^7.0.1",
"shortid": "^2.2.16",
"valid-url": "^1.0.9"
},
"devDependencies": {
"nodemon": "^2.0.21"
}
}
`
溃败\
url.js
{
"name": "url_shortner_service",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"config": "^3.3.9",
"express": "^4.18.2",
"mongoose": "^7.0.1",
"shortid": "^2.2.16",
"valid-url": "^1.0.9"
},
"devDependencies": {
"nodemon": "^2.0.21"
}
}
`
index.js
` const express = require('express');
const router = express.Router();
module.exports = router;
`
要求\
api.http
POST http://localhost:5000/api/url/shorten
Accept: application/json
{
"longUrl": "https://stackoverflow.com/questions/48419801/org-apache-http-conn-httphostconnectexception-connect-to-localhost19538-local"
}
模型\
const mongoose = require('mongoose');
const urlSchema = new mongoose.Schema({
urlCode: String,
longUrl: String,
shortUrl: String,
date: { type: String, default: Date.now}
});
module.exports = mongoose.model('Url', urlSchema);
配置
默认.json
{
"mongoURI": "mongodb+srv://apishort:<apishort>@cluster0.30vcjuk.mongodb.net/?retryWrites=true&w=majority",
"baseUrl": "http://localhost:5000"
}`
db.js
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db,
{
useNewUrlParser: true
});
console.log('MongoDB Connected...');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
我很确定它超级容易修复,但因为我是新手,我整天都在努力寻找解决方案,但就是找不到。
有人能帮忙吗?
教程中使用了 REST Client 插件。我试图在intellij中安装它但出现错误:
"Plugin "RESTClient" version was marked as incompatible."
也许这就是为什么 api.http 是红色的
所以我不知道是否有其他插件或其他方式来使用它并使其工作。