为什么我的快车子线路不工作



为什么这两个端点不能与routes.use一起工作http://127.0.0.1:3000/api/studentshttp://127.0.0.1:3000/api/teachers而我的http://127.0.0.1:3000/apihttp://127.0.0.1:3000/api/api工作正常。我正在使用express.js服务器和router()与typscript。

这是我的服务器。ts文件

import express from 'express';
import routes from './routes/index'
// create an application object
const app = express();
// defint a port
const port = 3000;
//apply router middleware to application
app.use('/api', routes);

// define a route handler for hompage
app.get('/', (req, res) => {
res.send('Hello, world!n welcome to the server.');
});

//start the express server
app.listen(port, ()=> {
console.log(`server started at localhost:${port}`)
});

this my index。/src/routes目录

import express from 'express';
import students from './api/students';
import teachers from './api/teachers';
const routes = express.Router();
// define a route handler for hompage
routes.get('/', (req, res) => {
res.send('connected to the server. main api route');
});
// define routes fro other paths
// routes.get('/api', (req, res) => {
//     res.send('connected to the server. secondary api route');
// });
routes.use('/api', routes);
routes.use('/students', students);
routes.use('/teachers', teachers);
export default routes;

和这个同学。/src/routes/api

import express from 'express';
const students = express.Router();

// define a route handler for api/students
students.get('/students', (req, res) => {
res.send('connected to the server. students route');
});
export default students;

这里为学生API的实际端点。/api/students/students因为在student.js文件中,路径从/students开始,所以最终URL将是
http://127.0.0.1:3000/api/students/students

此外,如果终点在学生。/students/然后它将与http://127.0.0.1:3000/api/students一起工作URL

最新更新