簡體   English   中英

Javascript:REST API Mongodb無法在Postman上連接

[英]Javascript: REST API Mongodb not connecting on Postman

我是JavaScript的新手,正在嘗試學習如何從計算機上的本地服務器構建REST API。 但是,當我在Postman上測試GET請求時,它總是返回一個錯誤:無法獲得任何響應。

REST API的目的是(a)存儲有關太陽系中行星的基本信息,(b)允許GET請求,(c)允許我使用POST在數據庫中添加更多條目。

當我去郵遞員時,我使用以下URL: localhost:8000/planets

我正在使用mongodb和mongoose。 我認為問題出在我的代碼中,因為我沒有收到服務器的響應,但我無法查明問題出在哪里。 謝謝。

    var express = require('express');
var bodyParser = require('body-parser');
var _ = require('lodash');
var mongoose = require('mongoose');

var app = express();

app.use(express.static('planet_pages'));

app.use(bodyParser.urlencoded({extended: false}));

app.use(bodyParser.json);

mongoose.Promise = global.Promise;
var promise = mongoose.connect('mongodb://localhost/planet_server', {
  useMongoClient: true,
});

promise.then(function(db){
  console.log('DATABASE CONNECTED!!');
}).catch(function(err){
  console.log('CONNECTION ERROR', err);
});

var Schema = mongoose.Schema;

var planetSchema = new Schema({
  name: String, 
  position: String, 
  moons: String,
  diameterInKm: String,
  daysInYear: String,
  temperature: String 
})

var Planet = mongoose.model('Planet', planetSchema);
Planet.collection.drop();

//*****RAW DATA*****

var planets = [{
  name: "Mercury",
  position: "Mercury is the first planet from the Sun",
  moons: "Mercury has no moons",
  diameterInKm: "Mercury's diameter is 4,879km",
  daysInYear: "A year on Mercury lasts just 88 days!",
  temperature: "The temperature on Mercury is a scorching 427C"},

  { name: "Venus",
    position: "Venus is the second planet from the Sun",
    moons: "Venus has no moons",
    diameterInKm: "Venus's diameter is 12,104km",
    daysInYear: "A year on Mercury lasts 225 days!",
    temperature: "The temperature on Mercury is 467C. Hot enough to melt lead!"
}];

//*****END OF RAW DATA*****

app.get('/planets', function(req, res){
  Planet.find({}).exec(function(err, planets){
    if(err) {
      return res.status(500).send(err);
    }
    return res.json(planets);
  });
});

app.listen(8000, function(){
  console.log('I am listening');
});

編輯:在app.use(express.static('planet_pages') ,planet_pages是我的項目文件夾中的一個文件夾,其中包含幾個HTML頁面,我希望這些頁面可以用來進行AJAX查詢。

另外,在app.get('/planets', function(req, res)行中,還有一個補充問題,我使用/planets作為擴展名,因為這是將數據保存在// ***中的URL的名稱**“原始數據”部分。我是從教程中獲得的,但是我不確定為什么要這樣做。如果有人能解釋一下,我將非常感謝。

還建議我使用Planet.collection.drop()來確保在我重新加載或更改數據庫時數據庫正確刷新。 由於我什至無法使GET請求正常工作,因此不確定是否需要此行。

另外,我還沒有放入POST請求代碼,因為直到讓GET請求功能正常工作,我才意識到這一點。

嘗試注釋掉app.use(bodyParser.json)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM