How to connect a JSON-Server with another server with different port?

时间:2019-04-17 02:15:16

标签: node.js json

I'm doing a simple website with a database that can be found on a json-server, typically like this one I found on the yt: https://www.youtube.com/watch?v=b4fvPUXGETo

My problem is I have no idea how the two server would communicate to each other. I'm a newbie to nodejs and any help would be appreciated.

The json-server is up and running on my http://localhost:3000/posts while the website im working on is running on my http://localhost:5000

Below is the db.json file

{
  "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"
    }
  ]
}

Snippet of the posts.js file:

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

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

Here is the index.js file

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}`));

I'm expecting that the http://localhost:5000/api/posts will preview the data inside the db.json but instead its displaying "http://localhost:3000/posts". What will be the workaround?

2 个答案:

答案 0 :(得分:0)

You can fix the 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 can help us get data from "http://localhost:3000/posts"

Actually you should console.log the data and change result according to the format you want

答案 1 :(得分:0)

您可以使用诸如axiosrequestrequest-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)
  }
});