节点上的 POST 方法.js在具有快速的 Replit 服务器上不起作用



我是后端新手,在Replit服务器中使用Node.js和express来部署文件应用程序:

然而,当我尝试执行一个帖子时,什么都没有发生!

var express = require('express');
var fs = require('fs');
const bodyParser = require('body-parser');
var app = express();
// Middlewares 
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/foo.json', function (req, res) {
console.log("It doesn't work!");
});

我只想通过express的POST方法将从index.html收集的数据保存到.json中(我不确定这是最好的方法(。我能做什么?

上面的代码不用于请求

app.post('/foo.json', function (req, res) {
console.log("It does not work");
});

这意味着您正在接受http://your_url/foo.json上的请求

它是一个端点。

对于您要做的事情,您必须使用xhr或类似axios的库从前端发出请求

# Axios CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ==" crossorigin="anonymous"></script>
axios.post('http://localhost:3002/foo', {
data: 'your_data_goes_here'
})

您的后端代码应该是

const express = require('express');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3002;
// Middlewares 
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/foo', (req, res) => {
console.log(req.body.data);
});
app.all('*', (req, res, next) => {
//  CORS
res.setHeader('Access-Control-Allow-Origin', '*');
//  Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
//  Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET','POST', 'OPTIONS');
next();
});
// Start the app
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});

最新更新