无法在控制台中发布到本地主机“ POST http:// localhost:8000 / sendpage 404(未找到)”

时间:2020-04-26 09:57:26

标签: javascript node.js post get axios

我无法将任何内容发布到我的localhost / sendpage(这是一个json文件)。 虽然我可以从中获取。为什么?控制台错误是“ POST http://localhost:8000/sendpage 404(未找到)”

服务器:

var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require('path');

var port=8000;
app.set('port',(process.env.PORT || port));

// Serve static assets from public/
app.use(express.static(path.join(__dirname, 'public/')));

var server = http.listen(app.get('port'), function () {
  console.log('Server listening on port ' + app.get('port'));
});


app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

app.get('/sendpage', function(req,res){
  res.json({
"id":40000,
"body":"Name: Vera\nEmail: vera.wid@gmail.com\n",
"read":true,"secret":false,
"direction":"in",
"readAt":"2020-04-24T13:45:41Z",
"createdAt":"2020-04-24T13:45:13Z",
"updatedAt":"2020-04-24T13:45:41Z",
"ChatWebsiteId":1,
"ChatInteractionId":249,
"UserId":11,
"ContactId":11584,
"AttachmentId":null,
"User":{"transport":null,"nat":null,"allow":null,"insecure":null,"permissions":[],"phoneBarEnableVideoRecording":false,"id":11,"fullname":"Bruce Wayne","alias":null}
})



});

连接到按钮的javascript函数:

function addMessage() {

  axios.post('http://localhost:8000/sendpage', {
  "id":40000,
  "body":"Name: Vera\nEmail: vera.wid@gmail.com\n",
  "read":true,"secret":false,
  "direction":"in",
  "readAt":"2020-04-24T13:45:41Z",
  "createdAt":"2020-04-24T13:45:13Z",
  "updatedAt":"2020-04-24T13:45:41Z",
  "ChatWebsiteId":1,
  "ChatInteractionId":249,
  "UserId":11,
  "ContactId":11584,
  "AttachmentId":null,
  "User":{"transport":null,"nat":null,"allow":null,"insecure":null,"permissions":[],"phoneBarEnableVideoRecording":false,"id":11,"fullname":"Bruce Wayne","alias":null}



})




.then(res=>console.log(res))
.catch(err=>console.error(err))
}

当我用get替换POST时,它起作用了吗?

1 个答案:

答案 0 :(得分:2)

您不会像使用GET那样处理快速代码中的POST请求

app.get('/sendpage', function(req,res){
  res.json({
  "id":40000,
  "body":"Name: Vera\nEmail: vera.wid@gmail.com\n",
  "read":true,"secret":false,
  "direction":"in",
  "readAt":"2020-04-24T13:45:41Z",
  "createdAt":"2020-04-24T13:45:13Z",
  "updatedAt":"2020-04-24T13:45:41Z",
  "ChatWebsiteId":1,
  "ChatInteractionId":249,
  "UserId":11,
  "ContactId":11584,
  "AttachmentId":null,
  "User":{"transport":null,"nat":null,"allow":null,"insecure":null,"permissions":[],"phoneBarEnableVideoRecording":false,"id":11,"fullname":"Bruce Wayne","alias":null}
})

您可以按如下所示添加它

app.post('/sendpage',function(req,res){
  //do something
})