【问题标题】:How to connect a JSON-Server with another server with different port?如何将 JSON-Server 与具有不同端口的另一台服务器连接?
【发布时间】:2019-09-07 04:39:00
【问题描述】:

我正在做一个简单的网站,其中包含一个可以在 json-server 上找到的数据库,通常就像我在 yt 上找到的这个:https://www.youtube.com/watch?v=b4fvPUXGETo

我的问题是我不知道两台服务器如何相互通信。我是 nodejs 的新手,任何帮助将不胜感激。

json 服务器在我的http://localhost:3000/posts 上启动并运行,而我正在处理的网站在我的http://localhost:5000 上运行

下面是db.json文件

{
  "posts": [
    {
      "userId": 1,
      "id": 1,
      "title": "ahkasdadad",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    }
  ]
}

posts.js 文件的片段:

const express = require('express');
const router = express.Router();
var endpoint = "http://localhost:3000/posts";

// Gets all posts
router.get('/', (req, res) => {
    res.send(endpoint);
});

这里是 index.js 文件

const express = require('express');
const path = require('path');
const app = express();
const logger = require('./middleware/logger');

// Innit middleware
// app.use(logger);

// Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({ extended:false }))

// Set static folder
app.use(express.static(path.join(__dirname, 'public')));

// Posts API route
app.use('/api/posts', require('./routes/api/posts'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

我希望http://localhost:5000/api/posts 会预览 db.json 中的数据,但会显示“http://localhost:3000/posts”。解决方法是什么?

【问题讨论】:

  • 你需要一个http clientaxios 来从一台服务器向另一台服务器发出请求。
  • 你能检查一下是 5000 还是 3000 正在运行/收听
  • 5000 和 3000 已启动并运行

标签: node.js json


【解决方案1】:

你可以修复 post.js

const express = require('express');
const router = express.Router();
const urllib = require('urllib')
const endpoint = "http://localhost:3000/posts";

router.get('/', (req, res) => {
  urllib.request(endpoint, function (err, data, res) {
    const result = data.toString()
    res.send(result);
  });
});

Urllib 可以帮助我们从“http://localhost:3000/posts”获取数据

其实你应该console.log数据并根据你想要的格式改变结果

【讨论】:

  • 嗨!感谢您的回答,res.send(result); 不起作用,但 console.log("Output Content : \n"+ result); 起作用,我阅读了 urllib 的文档,但无法得到任何答案。
  • 可以使用邮递员请求接口(@98​​7654322@),然后显示返回值
【解决方案2】:

您可以使用 axiosrequestrequest-promise(Promise 支持的请求版本)之类的库,例如:

var endpoint = "http://localhost:3000/posts";

// Gets all posts
const rp = require('request-promise');

router.get('/', (req, res) => {
  rp(endpoint)
    .then((data) => {
      res.send(data);
    })
    .catch(e => console.error(e))
});

或使用async/await

router.get('/', async (req, res) => {
  try {
    const data  = await rp(endpoint);
    res.send(data)
  } catch (e) {
    console.error(e)
  }
});

【讨论】:

  • 只是想澄清一下它应该是const rp = require('request-promise');。非常感谢,工作就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 2021-12-12
  • 1970-01-01
  • 2020-06-18
  • 2018-06-21
  • 2013-05-27
  • 1970-01-01
相关资源
最近更新 更多