[app.js]
onCreate = async (event) => {
event.preventDefault();
const clubData = new FormData(event.target)
console.log(clubData);
const post = await axios.post('/club', {
method: 'POST',
body: {
name : 'name',
intro : 'intro'
}
}).then(response => {console.log(post)})
}
这是路由器未分割的时候。
[server.js]
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(express.static(path.join(__dirname, '..', 'public/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.post('/club', function(req, res, next) {
res.send({ test: 'test'});
})
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.listen(PORT, () => {
console.log(`Check out the app at http://localhost:${PORT}`);
});
这时,我们能够看到来自Chrome开发人员窗口的数据。
但是,分割路由器后,会发生错误。
[server.js]
const express = require('express');
const path = require('path');
const engines = require('consolidate');
const bodyParser = require('body-parser');
const app = express();
const PORT = process.env.PORT || 4000;
var clubRouter = require('./router/clubRouter.js');
app.use(express.static(path.join(__dirname, '..', 'public/')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use('/club', clubRouter);
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.listen(PORT, () => {
console.log(`Check out the app at http://localhost:${PORT}`);
});
[clubRouter.js]
const router = require('express').Router();
const controller = require('../controller/clubController');
router.post('/club', function(req, res, next) {
res.send({ test: 'test'});
})
module.exports = router;
这时发生错误。
(POST http://localhost:3000/club 404(未找到))
我现在已经创建了一个带有react-app-create和webpack.config的项目。将代码添加到dev.js文件中。
devServer: {
port: 4000,
open: true,
proxy: {
"/": "http://localhost"
}
},
该代码也已添加到package.json文件中。
"proxy": "http://localhost:4000"
答案 0 :(得分:1)
clubRouter
安装在路径/club
上
这意味着任何/club*
请求都将被处理到clubRouter
clubRouter
还在路径/club
上注册了一个控制器,该控制器发送响应{ test: 'test'}
所以,
现在完整的路径应为=> /club/club
在您的React应用中,尝试此更改,它将起作用:
const post = await axios.post('/club/club', { ... })
如果您认为该路径不是您想要的路径,则可以在clubRouter
中注册控制器,如下所示:
router.post('/', function(req, res, next) {
res.send({ test: 'test'});
})
这样,您将可以使用以下旧路径来击中它:
const post = await axios.post('/club', { ... })