提交数据后获取localhost:4200 / api 404(未找到)

时间:2019-07-09 06:36:53

标签: node.js angular mongodb mean-stack

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

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

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

1 个答案:

答案 0 :(得分:0)

我认为您忘记了为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;````