简体   繁体   English

如何在后端捕获 POST 请求?

[英]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.

相关问题 无法将大量JSON POST请求解析到Kinvey后端 - Unable to parse bulk JSON POST request to Kinvey back-end 通过 Vuejs 和 axios 向 Laravel 后端提交 post 请求 - Submitting a post request through Vuejs and axios to a laravel back-end 如何从反应前端向节点后端发出发布请求? 获得 404 - How do I make a post request from a react front-end to a node back-end? Getting 404 我如何在 Vue.js 中将带有一些数组对象值的 Post 请求发送到我的后端 - How do i send Post request with some values of array object to my Back-end in Vue.js 在以POST(而不是GET)发送请求后,如何将对象作为html页面插入到来自后端的html元素中? - How to insert object as html page into html element which is coming from back-end after sending request as POST (and not GET)? 无法从 React 前端向 Node.js 后端发送 POST 请求 - Can't send POST request from React front-end to Node.js back-end 从前端javascript向后端node.js发送POST请求 - Send POST request from front-end javascript to back-end node.js javascript 将 blob 发布到后端 java - javascript post blob to back-end java Javascript - 来自服务器/后端的POST请求不起作用 - Javascript - POST request from server/back-end doesn't work NodeJS(后端)从POST调用接收数据,然后如何在ReactJS(前端)中显示? - NodeJS (back-end) receive data from POST call then how to show in ReactJS (front-end)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM