【问题标题】:GET localhost:4200/api 404 (Not Found) after submit data提交数据后 GET localhost:4200/api 404 (Not Found)
【发布时间】:2019-07-09 14:55:29
【问题描述】:

我下载了https://github.com/SinghDigamber/Angular8MeanstackAngularMaterial 并部署它。

但是,当我尝试保存数据并查看数据时,我总是得到 获取http://localhost:4200/api404(未找到)

add data to db error picture get data to db error picture

Angular v8.0.0 mongoDB v4.0.10 nodejs v12.2.0

//app.js

let express = require('express'),
  path = require('path'),
  mongoose = require('mongoose'),
  cors = require('cors'),
  bodyParser = require('body-parser'),
  dataBaseConfig = require('./database/db');

// Connecting mongoDB
mongoose.Promise = global.Promise;
mongoose.connect(dataBaseConfig.db, {
  useNewUrlParser: true
}).then(() => {
    console.log('Database connected sucessfully ')
  },
  error => {
    console.log('Could not connected to database : ' + error)
  }
)

// Set up express js port
const studentRoute = require('./routes/student.route')

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cors());

// Setting up static directory
app.use(express.static(path.join(__dirname, 'dist/angular8-meanstack-angular-material')));


// RESTful API root
app.use('/api', studentRoute)

// PORT
const port = process.env.PORT || 8000;

app.listen(port, () => {
  console.log('Connected to port ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// Index Route
app.get('/', (req, res) => {
  res.send('invaild endpoint');
});

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/angular8-meanstack-angular-material/index.html'));
});

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message);
  if (!err.statusCode) err.statusCode = 500;
  res.status(err.statusCode).send(err.message);
});

【问题讨论】:

    标签: node.js angular mongodb mean-stack


    【解决方案1】:

    我想你忘了为你的 API 路由导出 get 和 post 函数。

    你可以在 studentRoute 文件中创建这样的路由。

    var express = require('express');
    var router = express.Router();
    router.get('/', function (req, res, next) {
      return "Hello World";
    })
    router.post('/', function (req, res, next) {
      return "Hello World";
    })
    module.exports = router;````
    

    【讨论】:

    • 你不需要express.Router,你可以使用app.get
    猜你喜欢
    • 2017-01-12
    • 2018-10-27
    • 2021-11-20
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    相关资源
    最近更新 更多