Я пытаюсь получить данные mlab в консоль, используя node.js, но получаю эту ошибку - PullRequest
0 голосов
/ 15 сентября 2018

Я слежу за этим видео на YouTube: https://www.youtube.com/watch?v=PFP0oXNNveg&t=460s .i сделал то же самое, что и он, даже изменив код в соответствии с настоящим обновлением, выполнив поиск в Google (ошибки, которые я получил, когда пытался обновление).

Пожалуйста, помогите мне с этой проблемой !!!

Ошибка:

<code>GET http://localhost:3000/api/tasks 404 (Not Found)    zone.js:2969
scheduleTask    @   zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask  @   zone.js:407
onScheduleTask  @   zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask  @   zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask  @   zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @   zone.js:255
scheduleMacroTaskWithCurrentZone    @   zone.js:1114
(anonymous) @   zone.js:3001
proto.(anonymous function)  @   zone.js:1394
(anonymous) @   http.js:1103
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe  @   Observable.js:42
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe  @   Observable.js:28
push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call   @   map.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe  @   Observable.js:23
TasksComponent  @   tasks.component.ts:11
createClass @   core.js:9301
createDirectiveInstance @   core.js:9186
createViewNodes @   core.js:10406
callViewAction  @   core.js:10722
execComponentViewsAction    @   core.js:10641
createViewNodes @   core.js:10434
createRootView  @   core.js:10320
callWithDebugContext    @   core.js:11351
debugCreateRootView @   core.js:10838
push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create    @   core.js:8666
push../node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create    @   core.js:3315
push../node_modules/@angular/core/fesm5/core.js.ApplicationRef.bootstrap    @   core.js:4550
(anonymous) @   core.js:4358
push../node_modules/@angular/core/fesm5/core.js.PlatformRef._moduleDoBootstrap  @   core.js:4358
(anonymous) @   core.js:4324
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke    @   zone.js:388
onInvoke    @   core.js:3824
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke    @   zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run   @   zone.js:138
(anonymous) @   zone.js:872
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask    @   zone.js:421
onInvokeTask    @   core.js:3815
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask    @   zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask   @   zone.js:188
drainMicroTaskQueue @   zone.js:595
Promise.then (async)        
scheduleMicroTask   @   zone.js:578
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask  @   zone.js:410
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask  @   zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask @   zone.js:252
scheduleResolveOrReject @   zone.js:862
ZoneAwarePromise.then   @   zone.js:962
push../node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @   core.js:4353
./src/main.ts   @   main.ts:11
__webpack_require__ @   bootstrap:76
0   @   main.ts:12
__webpack_require__ @   bootstrap:76
checkDeferredModules    @   bootstrap:43
webpackJsonpCallback    @   bootstrap:30
(anonymous)

ERROR Response  core.js:1673 
 {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…<pre>Cannot GET /api/tasks
↵ ↵ ↵ ", status: 404, ok: false, statusText:« Not Found », заголовки: Headers,…} заголовки: Headers {_headers: Map (10), _normalizedNames: Map ( 10)} _ headers: Map (10) {"content-security-policy" => Array (1), "x-content-type-options" => Array (1), "x-powered-by" => Array (1), "allow" => Array (1), "access-control-allow-method" => Array (1),…} _normalizedNames: Map (10) {"content-security-policy" => "content -security-policy "," x-content-type-options "=>" x-content-type-options "," x-powered-by "=>" x-powered-by "," allow "=>" allow "," access-control-allow-method "=>" access-control-allow-Methods ",…} __ proto__: Objectok: falsestatus: 404statusText:" Not Found "тип: 2url:" http://localhost:3000/api/tasks"_body: "<! DOCTYPE html> ↵ ↵ ↵ ↵ Ошибка ↵ ↵ ↵
Cannot GET /api/tasks
↵ 101 ↵ "__ proto__: Bodyconstructor: ƒ Response (responseOptions) toString: ƒ () __ proto__: Объект defaultErrorLogger @ core.js: 1673 push ../ node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js: 1719 следующая @ core.js: 4319 schedulerFn @ core.js: 3555 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber .__ tryOrUnsub @ Subscriber.js: 209 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber.next @ Subscriber.js: 147 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber._next @ Subscriber.js: 80 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.next @ Subscriber.js: 55 push ../ node_modules / rxjs / _esm5 / internal / Subject.js.Subject.next @ Subject.js: 47 push ../ node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js: 3539 (анонимно) @ core.js: 3846 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invoke @ zone.js: 388 push ../ node_modules / zone.js / dist / zone.js.Zone.run @ zone.js: 138 push ../ node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js: 3783 onHandleError @ core.js: 3846 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.handleError @ zone.js: 392 push ../ node_modules / zone.js / dist / zone.js.Zone.runTask @ zone.js: 191 push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask @ zone.js: 496 ZoneTask.invoke @ zone.js: 485 таймер @ zone.js: 2054 setTimeout (async) scheduleTask @ zone.js: 2075 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.scheduleTask @ zone.js: 407 onScheduleTask @ zone.js: 297 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.scheduleTask @ zone.js: 401 push ../ node_modules / zone.js / dist / zone.js.Zone.scheduleTask @ zone.js: 232 push ../ node_modules / zone.js / dist / zone.js.Zone.scheduleMacroTask @ zone.js: 255 scheduleMacroTaskWithCurrentZone @ zone.js: 1114 (анонимно) @ zone.js: 2090 proto. (анонимная функция) @ zone.js: 1394 hostReportError @ hostReportError.js: 3 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber.error @ Subscriber.js: 181 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber._error @ Subscriber.js: 83 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error @ Subscriber.js: 61 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber._error @ Subscriber.js: 83 push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.Subscriber.error @ Subscriber.js: 61 onLoad @ http.js: 1059 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask @ zone.js: 421 onInvokeTask @ core.js: 3815 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask @ zone.js: 420 push ../ node_modules / zone.js / dist / zone.js.Zone.runTask @ zone.js: 188 push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask @ zone.js: 496 invokeTask @ zone.js: 1540 globalZoneAwareCallback @ zone.js: 1566 ошибка (асинхронная) customScheduleGlobal @ zone.js: 1666 нажимные ../ node_modules / zone.js / расстояние / zone.js.ZoneDelegate.scheduleTask @ zone.js: 407 onScheduleTask @ zone.js: 297 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.scheduleTask @ zone.js: 401 push ../ node_modules / zone.js / dist / zone.js.Zone.scheduleTask @ zone.js: 232 push ../ node_modules / zone.js / dist / zone.js.Zone.scheduleEventTask @ zone.js: 258 (анонимный) @ zone.js:1831 (анонимно) @ http.js: 1102 push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable._trySubscribe @ Observable.js: 42 push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable.subscribe @ Observable.js: 28 push ../ node_modules / rxjs / _esm5 / internal / operator / map.js.MapOperator.call @ map.js: 18 push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable.subscribe @ Observable.js: 23 TasksComponent @ tasks.component.ts: 11 createClass @ core.js: 9301 createDirectiveInstance @ core.js: 9186 createViewNodes @ core.js: 10406 ​​callViewAction @ core.js: 10722 execComponentViews@ core.js: 10641 createViewNodes @ core.js: 10434 createRootView @ core.js: 10320callWithDebugContext @ core.js: 11351 debugCreateRootView @ core.js: 10838 push ../ node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create @ core.js: 8666 push ../ node_modules / @ angular / core/fesm5/core.js.ComponentFactoryBoundToModule.create @ core.js: 3315 push ../ node_modules/@angular/core/fesm5/core.js.ApplicationRef.bootstrap @ core.js: 4550 (анонимно) @ core.js:4358 push ../ node_modules/@angular/core/fesm5/core.js.PlatformRef._moduleDoBootstrap @ core.js: 4358 (анонимный) @ core.js: 4324 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invoke @ zone.js: 388 onInvoke @ core.js: 3824 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invoke @ zone.js: 387 push ../ node_modules / zone.js / dist / zone.js.Zone.run @ zone.js: 138 (анонимный) @ zone.js: 872 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask @ zone.js: 421 onInvokeTask @ core.js: 3815 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask @ zone.js: 420 push ../ node_modules / zone.js / dist / zone.js.Zone.runTask@ zone.js: 188 diverMicroTaskQueue @ zone.js: 595 Promise.then (асинхронный) scheduleMicroTask @ zone.js: 578 push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.scheduleTask @ zone.js:410 push ../ node_modules / zone.js / dist / zone.js.Zone.scheduleTask @ zone.js: 232 push ../ node_modules / zone.js / dist / zone.js.Zone.scheduleMicroTask @ zone.js:252 scheduleResolveOrReject @ zone.js: 862 ZoneAwarePromise.then @ zone.js: 962 push ../ node_modules/@angular/core/fesm5/core.js.PlatformRef.bootstrapModule @ core.js: 4353 ./src/main.ts@ main.ts: 11 __webpack_require__ @ bootstrap: 76 0 @ main.ts: 12 __webpack_require__ @ bootstrap: 76 checkDeferredModules @ bootstrap: 43 webpackJsonpCallback @ bootstrap: 30 (анонимно) @ main.js: 1

Back-End Packet.json

{
  "name": "client",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "bootstrap": "^4.1.3",
    "core-js": "^2.5.4",
    "rxjs": "^6.0.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.7.0",
    "@angular/cli": "~6.1.5",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "typescript": "~2.7.2"
  }
}

server.js

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var port = 3000;
var index = require('./routes/index');
var tasks = require('./routes/tasks');

var app = express();

//view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');
app.engine('html', require('ejs').renderFile);

// Set Static Folder
app.use(express.static(path.join(__dirname, 'client')));

//Body parser Metaware

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

app.use('/', index);
app.use('/api', tasks);

app.listen(port, function(){
    console.log("server started at port "+port)
})

route-> index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next){
    res.render('index.html');

});

module.exports = router;

route-> tasks.js

var express = require('express');
var router = express.Router();
var mongojs =require('mongojs');
var db = mongojs('mongodb://Revanth:revanth99@ds161790.mlab.com:61790/revanth', ['tasks']);

//GET All Tasks
router.get('/tasks', function(req, res, next){
    db.tasks.find(function(err, tasks){
        if(err){
            res.send(err);
        }
        res.json(tasks);
    });

});
//GET Single task
router.get('/task/:id',function(req, res, next){
    db.tasks.findOne({_id: mongojs.ObjectId(req.params.id)}, function(err, task){
        if(err){
            res.send(err);
        }
        res.json(task);
    });
});

//Save Task
router.post('/task', function(res, req, next){
    var task = req.body;
    if(!task.title || (task.isDone + '')){
        res.statusCode(404);
        res.json({
            "error": "Bad Data"
        });
    } else{
        db.tasks.save(task, function(err, task){
            if(err){
                res.send(err);
            }
            ress.json(task);
        })
    }
});

//Delete Task
router.delete('/task/:id',function(req, res, next){
    db.tasks.remove({_id: mongojs.ObjectId(req.params.id)}, function(err, task){
        if(err){
            res.send(err);
        }
        res.json(task);
    });
});

//Update Task
router.put('/task/:id',function(req, res, next){
    var task = req.body;
    var updTask = {};

    if(task.isDone){
        updTask.isDone = task.isDone;
    }

    if(task.title){
        update.title = task.title;
    }
    if(!update){
        res.status(400);
        res.json({
            "error": "Bad Data"
        });
    } else{
        db.tasks.update({_id: mongojs.ObjectId(req.params.id)},updTask, {}, function(err, task){
            if(err){
                res.send(err);
            }
            res.json(task);
        });
    }


});



module.exports = router;

Front-END app-> Component-> tasks-> tasks.component.ts

import { Component } from '@angular/core';
import { TaskService } from '../../services/task.service'
@Component({
  selector: 'tasks',
  templateUrl: './tasks.component.html'
})

export class TasksComponent {
    constructor(private taskService:TaskService){
            this.taskService.getTasks()
                .subscribe(tasks => {
                    console.log(tasks);
                });
    }
}

app-> services-> task.service.ts

import { Component } from '@angular/core';
import { TaskService } from '../../services/task.service'
@Component({
  selector: 'tasks',
  templateUrl: './tasks.component.html'
})

export class TasksComponent {
    constructor(private taskService:TaskService){
            this.taskService.getTasks()
                .subscribe(tasks => {
                    console.log(tasks);
                });
    }
}

apps-> app.component.ts

import { Component } from '@angular/core';
import { TaskService } from './services/task.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[ TaskService ]
})
export class AppComponent {
  title = 'client';
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from'@angular/http';
import { AppComponent } from './app.component';
import { TasksComponent } from './components/tasks/tasks.component';

@NgModule({
  declarations: [
    AppComponent,
    TasksComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

1 Ответ

0 голосов
/ 16 сентября 2018

Прежде всего вам необходимо определить, где именно может быть проблема. Попробуйте использовать почтальон, используя правильные глаголы http, для вызова ваших конечных точек API. Убедитесь, что сервер работает и конечные точки правильны, как определено в rout.tryчтобы записать данные, которые вы запросили из db, в консоли. console.log(task) or logging the error таким образом, вы сможете узнать, где именно может быть проблема, и соответственно спросить / решить

...