Node.js]1'de HTTP POST
yönteminden gönderilen form verilerini (form[method="post"]
) ve dosya yüklemelerini nasıl çıkarırsınız?
Belgeleri okudum, Google'da araştırdım ve hiçbir şey bulamadım.
function (request, response) {
//request.post????
}
Kütüphane ya da hack var mı?
quystring`](https://nodejs.org/api/querystring.html#querystring_query_string) modülünü kullanabilirsiniz:
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
Örneğin, yaş
adında bir girdi
alanınız varsa, buna post
değişkenini kullanarak erişebilirsiniz:
console.log(post.age);
Express]4 (Node.js için yüksek performanslı, yüksek sınıf web geliştirme) kullanıyorsanız, bunu yapabilirsiniz:
HTML:
<form method="post" action="/">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
API istemcisi:
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: {
name: "John",
email: "[email protected]"
}
})
});
Node.js: (Express v4.16.0'dan beri)
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
// Access the parse results as request.body
app.post('/', function(request, response){
console.log(request.body.user.name);
console.log(request.body.user.email);
});
Node.js: (Express <4.16.0 için)
const bodyParser = require("body-parser");
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
app.post("/", function (req, res) {
console.log(req.body.user.name)
});