[英]How to catch POST request on back-end?
<!doctype html>
<head>
</head>
<body>
<script>
const Http = new XMLHttpRequest();
const url='http://localhost:4550/users';
Http.open("POST", url);
Http.send("hey");
Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}
</script>
</body>
</html>
//user.js
var express = require('express');
var router = express.Router();
var array = [];
/* GET users listing. */
router.get('/', (req, res, next) => {
res.send('respond with a resource1');
});
router.post('/', (req, res, next) => {
res.send('respond with a resource2');
});
module.exports = router;
//app.js
const express = require('express')
const app = express();
app.get('/',(req,res)=> {
console.log('lior');
res.send('api running 2')});
app.use('/users',require('./routes/users'))
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
const PORT = process.env.PORT || 4550;
app.listen(PORT,()=> console.log('server started on port ${PORT}'));
I am new with connecting client and server side, and it might be why I couldn't find an answer for my question.我是连接客户端和服务器端的新手,这可能是我找不到问题的答案的原因。 Is a simple question.是一个简单的问题。
As you can see I want to send "hey" from the client to the server(user.js).如您所见,我想从客户端向服务器(user.js)发送“嘿”。 However I don't know how does I catch the response on the server side.但是我不知道如何在服务器端捕获响应。
I know that a "hey" or neither the code make much sense, but is just an example to make things simple, I just wondering how does the server side could catch and handle the data.我知道“嘿”或代码都没有多大意义,但这只是使事情变得简单的一个示例,我只是想知道服务器端如何捕获和处理数据。
Thanks in advance!提前致谢!
When you post data, specify how you are encoding it.发布数据时,请指定如何对其进行编码。 It's generally best to use a standard encoding method rather than POSTing plain text.通常最好使用标准编码方法而不是 POST 纯文本。 (Also don't start variable names with capital letters unless they are constructor functions) (也不要以大写字母开头变量名,除非它们是构造函数)
const http = new XMLHttpRequest();
const url = 'http://localhost:4550/users';
const data = JSON.stringify({ value: "hey" });
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/json");
http.send(data);
http.onreadystatechange = (e) => {
console.log(http.responseText)
}
Then in your server side code, use a body parser to decode the data.然后在您的服务器端代码中,使用正文解析器对数据进行解码。
Since you are using an absolute URL in the request, it seems likely that you are making a cross-origin request so you also need to grant permission using CORS .由于您在请求中使用了绝对 URL,因此您可能正在发出跨域请求,因此您还需要使用CORS授予权限。
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
const port = 4550
const jsonParser = bodyParser.json()
const corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200
};
const corsMiddleware = cors(corsOptions)
app.get('/', (req, res) => res.send('Hello World!'))
app.get('/users', (req, res, next) => {
res.send('respond with a resource1');
});
app.options("/users", corsMiddleware)
app.post('/users', corsMiddleware, jsonParser, (req, res, next) => {
// data is in `req.body` (which will have a `value` property because the object on the client does)
res.send('respond with a resource2');
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
(The above is untested and may have minor errors in it) (以上未经测试,可能有小错误)
Please send serialized data as below:请发送序列化数据如下:
const http = new XMLHttpRequest();
const url = 'http://localhost:4550/users';
const data = JSON.stringify("hey");
http.open("POST", url);
http.setRequestHeader("Content-Type", "application/json");
http.send(data);
You need to use bodyParser
package您需要使用bodyParser
包
npm install body-parser
const bodyParser = require("body-parser");
and before setting up routes use it as below :并在设置路线之前使用它如下:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Don't forget to allow the headers declaration as below :不要忘记允许标题声明如下:
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST"
);
next();
});
and now you can read your data as below现在你可以阅读你的数据如下
router.post('/users', (req, res, next) => {
console.log(req.body);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.