Javascript 带有socket.io结果的app.post无法获取
我正在为我和我的朋友制作一个小应用程序,但由于某些原因它不起作用。我对socket.io还不太熟悉,所以我无法自己解决这个问题。。。 因此,我使用以下服务器端代码:Javascript 带有socket.io结果的app.post无法获取,javascript,node.js,socket.io,Javascript,Node.js,Socket.io,我正在为我和我的朋友制作一个小应用程序,但由于某些原因它不起作用。我对socket.io还不太熟悉,所以我无法自己解决这个问题。。。 因此,我使用以下服务器端代码: var-app=require('express')(); var http=require('http')。createServer(应用程序); var io=require('socket.io')(http); const bodyParser=require('body-parser'); use(bodyParser.j
var-app=require('express')();
var http=require('http')。createServer(应用程序);
var io=require('socket.io')(http);
const bodyParser=require('body-parser');
use(bodyParser.json());
app.post('/initiate',(请求、响应)=>{
控制台日志(“yey1”);
const{body}=请求;
发起(身体命令);
});
http.listen(3000,()=>{
console.log(“在端口3000上侦听”);
});
功能启动(命令){
控制台日志(“yey”);
io.emit(“命令”,command);
}
use(bodyParser.urlencoded({extended:false}));
app.set('views','u dirname+'/public');
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');
应用程序获取(“/”,(请求,请求)=>{
res.render(uu dirname+'/public/index.html',{command:“waiting…”);
});```
无论何时尝试连接到/initiate,它都会说“无法获取/initiate”。
我做错了什么?
因此,有很多事情我们需要解决,我们将一边解释一边解决
/*
* So first thing you need to understand is Express or HTTP is a static server, so this
* means that once you start it or call the listen function, you cant really change
* anything after that, so you want to configure all your routes properly before calling
* the listen function.
*/
// use const because its not like your gonna reinstantiate these anytime soon
const bodyParser = require('body-parser');
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.use(bodyParser.json());
// This route has to be configured first because if you define it last, it will
// overwrite the initiate route that you have.
app.get('/', (req, res) => {
res.render(__dirname + '/public/index.html', {command: "Awaiting..."});
});
// The reason you're getting the GET error when browsing to it is because this route,
// has been configured to use the POST method so if you want it to be accessible on a
// GET method then use app.get
app.get('/initiate', (request, response) => {
console.log("yey1");
const { body } = request;
initiate(body.command);
});
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
// So you see, you have to setup the whole server first before starting it up
http.listen(3000, () => {
console.log('Listening on port 3000');
});
function initiate(command){
console.log("yey");
io.emit("command", command);
}
我希望这能帮助你克服学习中的一些障碍,祝你好运