【问题标题】:GET http://localhost:3000/api/jobdetail 404 (Not Found)GET http://localhost:3000/api/jobdetail 404(未找到)
【发布时间】:2018-11-22 00:43:02
【问题描述】:

在我的数据库(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@ 工作数据.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:3 r.scheduleTask @ polyfills.js:3 r.scheduleMicroTask@polyfills.js:3 f@polyfills.js:3 c@polyfills.js:3(匿名)@polyfills.js:3 webpackJsonpCallback@ 引导 ac2fad340272940ddf57:21(匿名)@ 0.js:1 core.js:1448 错误响应{_body:“↵↵↵无法获取 /api/jobdetail↵↵↵”,状态:404, ok: false, statusText: "Not Found", headers: Headers, ...}headers: 标题 {_headers: Map(1), _normalizedNames: Map(1)}ok: falsestatus: 404statusText:“未找到”类型:2url: "http://localhost:3000/api/jobdetail"_body: "↵↵↵↵错误↵↵↵

无法获取
/api/jobdetail
↵↵↵"proto:正文 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 @ 订阅者.js:186订阅者._next @订阅者.js:126订阅者.next @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:1639 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:3 r.scheduleTask @ polyfills.js:3 r.scheduleMicroTask@polyfills.js:3 f@polyfills.js:3 c@polyfills.js:3(匿名)@polyfills.js:3 webpackJsonpCallback@ 引导 ac2fad340272940ddf57:21(匿名)@ 0.js:1

我也尝试过使用邮递员将错误显示为

错误

无法获取 /api/jobdetail

【问题讨论】:

  • 你好,错误信息看起来很简单,你的问题到底是什么?
  • 为什么我无法得到回复

标签: node.js mongodb express ionic-framework mean-stack


【解决方案1】:

【讨论】:

    【解决方案2】:

    您在路由文件中引用了一个名为 jobDetails 的变量,但该变量并未在任何地方声明。要么这就是问题所在,要么你没有发布所有代码。

    这是有问题的路线,请注意下面的第 4 行:

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

    【讨论】:

      【解决方案3】:

      是的,这并不神秘。您正在暴露路线:

      /jobdetail
      

      不是:

      /api/jobdetail
      

      404 错误告诉你这一点。

      【讨论】:

      • 写一个测试路线,确保它有效。您的服务器绝对不会暴露该端点。
      【解决方案4】:

      这样改,我觉得你无条件找工作详情:

      jobDetails.find({}, (err,jobs) => {
      if(err) {
        console.log(err);
      }
      else {
        res.json(jobs);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-14
        • 1970-01-01
        • 2019-07-24
        • 1970-01-01
        • 2021-02-22
        • 2021-03-11
        • 1970-01-01
        • 1970-01-01
        • 2021-05-19
        相关资源
        最近更新 更多