В моей базе данных (MongoDB) у меня есть 2 коллекции, которые называются users и jobdetail. Я пытаюсь подключиться ко второй коллекции jobdetail и получить данные.Это мой код app.js.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
// Connect To Database
mongoose.connect(config.database);
// On Connection
mongoose.connection.on('connected', () => {
console.log('Connected to database '+config.database);
});
// On Error
mongoose.connection.on('error', (err) => {
console.log('Database error: '+err);
});
const app = express();
const port = 3000;
const users = require('./routes/users');
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.send('Invalid endpoint');
});
// Body Parser Middleware
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.use('/users', users);
// CORS Middleware
app.use(cors());
app.listen(port, () => {
console.log("Server started on port:", port);
});
Это мой файл маршрутов
const express = require('express');
const router = express.Router();
const passport = require('passport');
const config = require('../config/database');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
// Register
router.post('/register', (req, res, next) => {
//code
});
User.addUser(newUser, (err, user) => {
if(err){
res.json({success: false, msg:'Failed to register user'});
} else {
res.json({success: true, msg:'User registered'});
}
});
});
// Update User
router.post('/update', function(req, res, next) {
//code
})
// Authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if(err) throw err;
if(!user){
return res.json({success: false, msg: 'User not found'});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
const token = jwt.sign(user, config.secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'JWT '+token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({success: false, msg: 'Wrong password'});
}
});
});
});
//get job details
router.get('/jobdetail', function(req,res) {
console.log('fetching jobs');
jobDetails.find(function(err,jobs) {
if(err) {
console.log(err);
}
else {
res.json(jobs);
}
});
});
// Profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
res.json({user: req.user});
});
module.exports = router;
Это файл provider.ts
getJobDetails() {
if(this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve =>{
this.http.get('http://localhost:3000/api/jobdetail')
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
Я получаюошибка типа
polyfills.js: 3 GET http://localhost:3000/api/jobdetail 404 (не найдено) s @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3 onScheduleTask @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3 r.scheduleTask @ polyfills.js: 3 r.scheduleMacroTask @ polyfills.js: 3 (анонимно) @ polyfills.js: 3 o. (Анонимная функция) @ polyfills.js: 2(анонимно) @ http.js: 1640 Observable._trySubscribe @ Observable.js: 172 Observable.subscribe @ Observable.js: 160 MapOperator.call @ map.js: 56 Observable.subscribe @ Observable.js: 157 (аноним) @ jobs-data.ts: 23 t @ polyfills.js: 3 webpackJsonp.181.JobsDataProvider.getJobDetails @ jobs-data.ts: 20 webpackJsonp.260.FeedsPage.ionViewDidLoad @ feeds.ts: 63 ViewController._lifecycle @ view-controller.js: 486 ViewController._didLoad @ view-controller.js: 369 NavControllerBase._didLoad @ nav-controller-base.js: 768 t.invoke @ polyfills.js: 3 onInvoke @ core.js: 4749 t.invoke @ polyfills.js: 3 r.run @ polyfills.js: 3 NgZone.run @ core.js: 4566 NavControllerBase._viewAttachToDOM @ nav-controller-base.js: 463 NavControllerBase._transition @ nav-controller-base.js: 540 (анонимно) @ nav-controller-base.js: 261 t.invoke @ polyfills.js: 3 onInvoke @ core.js: 4749 t.invoke @ polyfills.js: 3 r.run @ polyfills.js: 3 (анонимно) @ polyfills.js: 3 t.invokeTask @ polyfills.js: 3 onInvokeTask @ core.js: 4740 t.invokeTask @ polyfills.js: 3 r.runTask @polyfills.js: 3 o @ polyfills.js: 3 Promise.then (async) r @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3 onScheduleTask @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3r.scheduleTask @ polyfills.js: 3 r.scheduleMicroTask @ polyfills.js: 3 f @ polyfills.js: 3 c @ polyfills.js: 3 (анонимно) @ polyfills.js: 3 webpackJsonpCallback @ bootstrap ac2fad340272940ddf57: 21 (анонимно)@ 0.js: 1 core.js: 1448 Ответ об ошибке {_body: "↵↵↵Не могу получить / api / jobdetail↵↵↵", статус: 404, нормально: false, statusText: «Not Found», заголовки: Headers,…} заголовки: Headers {_headers: Map (1), _normalizedNames: Map (1)} ok: falsestatus: 404statusText: «Not Found» тип: 2url: "http://localhost:3000/api/jobdetail"_body: "Ошибка"
Cannot GET
/api/jobdetail
↵↵↵ "
прото : тело defaultErrorLogger @ core.js: 1448 ErrorHandler.handleError @ core.js: 1509 IonicErrorHandler.handleError @ ionic-error-handler.js: 61 следующий @ core.js: 5497 schedulerFn @ core.js: 4331 SafeSubscriber .__ tryOrUnsub @ Subscriber.js: 239 SafeSubscriber.next @ Subscriber.js: 186 Подписчик._следующий @ Подписчик.js: 126 Подписчик.@ Subscriber.js: 90 Subject.next @ Subject.js: 55 EventEmitter.emit @ core.js: 4311 (анонимно) @ core.js: 4771 t.invoke @ polyfills.js: 3 r.run @ polyfills.js:3 NgZone.runOutsideAngular @ core.js: 4697 onHandleError @ core.js: 4771 t.handleError @ polyfills.js: 3 r.runTask @ polyfills.js: 3 e.invokeTask @ polyfills.js: 3 p @ polyfills.js:2 v @ polyfills.js: 2 ошибка (асинхронная) O @ polyfills.js: 2 t.scheduleTask @ polyfills.js: 3 onScheduleTask @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3 r.scheduleTask @ polyfills.js: 3 r.scheduleEventTask @ polyfills.js: 3 (анонимный) @ polyfills.js: 2 (анонимный) @ http.js: 1639Observable._trySubscribe @ Observable.js: 172 Observable.subscribe @ Observable.js: 160 MapOperator.call @ map.js: 56 Observable.subscribe @ Observable.js: 157 (анонимный) @ jobs-data.ts: 23 т @ polyfills.js: 3 webpackJsonp.181.JobsDataProvider.getJobDetails @ jobs-data.ts: 20 webpackJsonp.260.FeedsPage.ionViewDidLoad @ feeds.ts: 63 ViewController._lifecycle @ view-controller.js: 486 ViewController._didLoad @.js: 369 NavControllerBase._didLoad @ nav-controller-base.js: 768 t.invoke @ polyfills.js: 3 onInvoke @ core.js: 4749 t.invoke @ polyfills.js: 3 r.run @ polyfills.js: 3 NgZone.run @ core.js: 4566 NavControllerBase._viewAttachToDOM @ nav-controller-base.js: 463 NavControllerBase._transition @ nav-controller-base.js: 540 (анонимно) @ nav-controller-base.js: 261 t.invoke @ polyfills.js: 3 onInvoke @ core.js: 4749 t.invoke @ polyfills.js: 3 r.run @ polyfills.js:3 (анонимно) @ polyfills.js: 3 t.invokeTask @ polyfills.js: 3 onInvokeTask @ core.js: 4740 t.invokeTask @ polyfills.js: 3 r.runTask @ polyfills.js: 3 o @ polyfills.js:3 Promise.then (async) r @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3 onScheduleTask @ polyfills.js: 3 t.scheduleTask @ polyfills.js: 3 r.scheduleTask @ polyfills.js: 3 r.scheduleMicroTask @ polyfills.js: 3 f @ polyfills.js: 3 c @ polyfills.js: 3 (анонимно) @ polyfills.js: 3 webpackJsonpCallback @ bootstrap ac2fad340272940ddf57: 21 (анонимно) @ 0.js: 1
Я также пробовал использовать почтальон, он отображал ошибку как
Ошибка
Cannot GET /api/jobdetail