Node.js에서 POST 데이터를 처리하는 방법은 무엇입니까?
데이터는 합니까?form[method="post"]및 ) 및 HTTP 전된일파업로드서에송▁sent▁uploadsPOSTNode.js의 메서드?
문서를 읽었는데, 검색해보니 아무것도 없었어요.
function (request, response) {
//request.post????
}
도서관이나 해킹이 있습니까?
모듈을 사용할 수 있습니다.
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.
});
}
}
를 들어,이 자, 예, 만이 있다면,input이 " " " 인 age 변를사여액수있다니습세할스용하수▁the▁variable▁it▁using▁access다▁you니있▁could습을 사용하여 접근할 수 있었습니다.post:
console.log(post.age);
Express(Node.js용 고성능 고급 웹 개발)를 사용하는 경우 다음 작업을 수행할 수 있습니다.
HTML:
<form method="post" action="/">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
API 클라이언트:
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: {
name: "John",
email: "john@example.com"
}
})
});
Node.js: (Express v4.16.0 이후)
// 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의 경우)
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)
});
여기에 있는 많은 답변들은 더 이상 좋은 관행이 아니거나 아무것도 설명하지 않기 때문에 이 글을 쓰는 것입니다.
기본 사항
http.createServer의 콜백이 호출될 때는 서버가 요청에 대한 헤더를 실제로 모두 수신했지만 데이터가 아직 수신되지 않았을 수 있으므로 기다려야 합니다.http 요청 개체(http)입니다.수신 메시지 인스턴스)는 실제로 읽을 수 있는 스트림입니다.읽을 수 있는 스트림에서는 데이터 청크가 도착할 때마다 이벤트가 발생하고(콜백을 등록한 것으로 가정) 모든 청크가 도착하면 이벤트가 발생합니다.다음은 이벤트를 청취하는 방법에 대한 예입니다.
http.createServer((request, response) => {
console.log('Now we have a http message with headers but no data yet.');
request.on('data', chunk => {
console.log('A chunk of data has arrived: ', chunk);
});
request.on('end', () => {
console.log('No more data');
})
}).listen(8080)
버퍼를 문자열로 변환하는 중
이를 시도하면 청크가 버퍼라는 것을 알 수 있습니다.만약 당신이 이진 데이터를 다루지 않고 대신 문자열로 작업해야 한다면, 스트림이 지정된 인코딩으로 해석된 문자열을 내보내고 멀티바이트 문자를 적절하게 처리하는 request.setEncoding 메서드를 사용하는 것이 좋습니다.
청크 버퍼링
이제 각 청크 자체에는 관심이 없기 때문에 이 경우에는 다음과 같이 버퍼링하기를 원할 수 있습니다.
http.createServer((request, response) => {
const chunks = [];
request.on('data', chunk => chunks.push(chunk));
request.on('end', () => {
const data = Buffer.concat(chunks);
console.log('Data: ', data);
})
}).listen(8080)
여기서 Buffer.concat은 모든 버퍼를 연결하고 하나의 큰 버퍼를 반환하기만 하면 됩니다.다음과 같은 기능을 하는 콘캣 스트림 모듈을 사용할 수도 마찬가지입니다.
const http = require('http');
const concat = require('concat-stream');
http.createServer((request, response) => {
concat(request, data => {
console.log('Data: ', data);
});
}).listen(8080)
내용 구문 분석 중
파일이 없는 HTML 양식 POST 제출을 수락하거나 기본 컨텐츠 유형으로 jQuery agax 호출을 처리하려는 경우 컨텐츠 유형은 다음과 같습니다.application/x-www-form-urlencoded와 함께utf-8부호화쿼리 문자열 모듈을 사용하여 쿼리 문자열을 역직렬화하고 속성에 액세스할 수 있습니다.
const http = require('http');
const concat = require('concat-stream');
const qs = require('querystring');
http.createServer((request, response) => {
concat(request, buffer => {
const data = qs.parse(buffer.toString());
console.log('Data: ', data);
});
}).listen(8080)
내용 유형이 JSON인 경우 qs.parse 대신 JSON.parse를 사용하면 됩니다.
파일을 다루거나 멀티파트 컨텐츠 유형을 다루는 경우에는 처리 시 발생하는 모든 고통을 제거하는 가공할 만한 것을 사용해야 합니다.멀티파트 콘텐츠를 위한 유용한 링크와 모듈을 게시한 다른 답변을 보십시오.
배관
내용을 구문 분석하지 않고 다른 곳으로 전달하려는 경우, 예를 들어 다른 http 요청에 데이터로 보내거나 파일에 저장하는 것이 좋습니다. 코드가 적고 배압을 더 잘 처리하므로 메모리가 더 적게 걸리고 경우에 따라 더 빠릅니다.
따라서 내용을 파일에 저장하려면 다음을 수행합니다.
http.createServer((request, response) => {
request.pipe(fs.createWriteStream('./request'));
}).listen(8080)
데이터 양 제한
다른 답변에서 언급했듯이 악의적인 클라이언트는 특정 제한을 초과하는 데이터를 보내는 요청을 삭제하지 않도록 보호하기 위해 응용 프로그램을 중지하거나 메모리를 채우는 데 엄청난 양의 데이터를 보낼 수 있습니다.라이브러리를 사용하여 수신 데이터를 처리하지 않는 경우.지정된 제한에 도달하면 요청을 중단할 수 있는 스트림 미터와 같은 것을 사용할 것을 제안합니다.
limitedStream = request.pipe(meter(1e7));
limitedStream.on('data', ...);
limitedStream.on('end', ...);
또는
request.pipe(meter(1e7)).pipe(createWriteStream(...));
또는
concat(request.pipe(meter(1e7)), ...);
NPM 모듈
위에서 단순히 내용을 버퍼링하고 구문 분석하기 위해 HTTP 요청 본문을 사용하는 방법에 대해 설명했지만, 에지 사례를 더 잘 처리할 수 있기 때문에 이러한 모듈 중 하나를 사용하는 것이 좋습니다.급행은 바디 파서를 사용하는 것을 추천합니다.코아도 비슷한 모듈이 있습니다.
틀을 사용하지 않으면 몸이 꽤 좋습니다.
누군가 RAM을 플러딩하려고 하면 연결을 끊어야 합니다!
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
request.connection.destroy();
}
});
request.on('end', function () {
var POST = qs.parse(body);
// use POST
});
}
}
다음은 여기에 게시된 다른 답변과 기사를 기반으로 한 매우 간단한 무프레임워크 래퍼입니다.
var http = require('http');
var querystring = require('querystring');
function processPost(request, response, callback) {
var queryData = "";
if(typeof callback !== 'function') return null;
if(request.method == 'POST') {
request.on('data', function(data) {
queryData += data;
if(queryData.length > 1e6) {
queryData = "";
response.writeHead(413, {'Content-Type': 'text/plain'}).end();
request.connection.destroy();
}
});
request.on('end', function() {
request.post = querystring.parse(queryData);
callback();
});
} else {
response.writeHead(405, {'Content-Type': 'text/plain'});
response.end();
}
}
사용 예:
http.createServer(function(request, response) {
if(request.method == 'POST') {
processPost(request, response, function() {
console.log(request.post);
// Use request.post here
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
});
} else {
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
response.end();
}
}).listen(8000);
데이터를 JSON으로 인코딩한 다음 Node.js로 전송하면 더 깨끗해집니다.
function (req, res) {
if (req.method == 'POST') {
var jsonString = '';
req.on('data', function (data) {
jsonString += data;
});
req.on('end', function () {
console.log(JSON.parse(jsonString));
});
}
}
웹 프레임워크를 설치하지 않고 이 사소한 작업을 수행하는 방법을 궁금해하는 사람들을 위해 저는 이것을 함께 할 수 있었습니다.거의 생산이 준비되지 않았지만 작동하는 것 같습니다.
function handler(req, res) {
var POST = {};
if (req.method == 'POST') {
req.on('data', function(data) {
data = data.toString();
data = data.split('&');
for (var i = 0; i < data.length; i++) {
var _data = data[i].split("=");
POST[_data[0]] = _data[1];
}
console.log(POST);
})
}
}
사용할 수 있습니다.body-parserNode.js 본문 구문 분석 미들웨어.
첫 번째 로드body-parser
$ npm install body-parser --save
몇 가지 예제 코드
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(function (req, res) {
var post_data = req.body;
console.log(post_data);
})
자세한 설명서는 여기에서 확인할 수 있습니다.
참조: https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
노드 처리 능력을 사용하는 경우 다음과 같은 방법이 있습니다.
var formidable = require("formidable");
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
console.log(fields.parameter1);
console.log(fields.parameter2);
// ...
});
순수 Node.js를 사용하려면 아래와 같이 POST 데이터를 추출할 수 있습니다.
// Dependencies
const StringDecoder = require('string_decoder').StringDecoder;
const http = require('http');
// Instantiate the HTTP server.
const httpServer = http.createServer((request, response) => {
// Get the payload, if any.
const decoder = new StringDecoder('utf-8');
let payload = '';
request.on('data', (data) => {
payload += decoder.write(data);
});
request.on('end', () => {
payload += decoder.end();
// Parse payload to object.
payload = JSON.parse(payload);
// Do smoething with the payload....
});
};
// Start the HTTP server.
const port = 3000;
httpServer.listen(port, () => {
console.log(`The server is listening on port ${port}`);
});
»'body-parser'npm에서.
그러면 당신의 앱에서.
var bodyParser = require('body-parser');
그럼 당신은 글을 써야 합니다.
app.use(bodyParser.json())
app.ts 모듈에서
포함한다는 것을 명심하세요.
app.use(bodyParser.json())
모듈 선언의 맨 위 또는 앞에 표시됩니다.
예:
app.use(bodyParser.json())
app.use('/user',user);
사용할 경우
var postdata = req.body;
데를함청않으와 함께 data할 수 .readable다음과 같은 콜백:
// Read Body when Available
request.on("readable", function(){
request.body = '';
while (null !== (request.body += request.read())){}
});
// Do something with it
request.on("end", function(){
request.body //-> POST Parameters as String
});
이 접근 방식은 수신 요청을 수정하지만 응답을 완료하는 즉시 요청이 가비지 수집되므로 문제가 되지 않습니다.
만약 여러분이 거대한 몸을 두려워한다면, 먼저 몸의 크기를 확인하는 것이 진보된 접근법일 것입니다.
은 다을수야합니다해신음▁the▁you를 받아야 .POST청의데이사터를 사용한 된 데이터request.on('data', function(chunk) {...})
const http = require('http');
http.createServer((req, res) => {
if (req.method == 'POST') {
whole = ''
req.on('data', (chunk) => {
# consider adding size limit here
whole += chunk.toString()
})
req.on('end', () => {
console.log(whole)
res.writeHead(200, 'OK', {'Content-Type': 'text/html'})
res.end('Data received.')
})
}
}).listen(8080)
jh가 제안한 대로 표시된 위치에 크기 제한을 추가하는 것을 고려해야 합니다.
여러 가지 방법이 있습니다.하지만 제가 아는 가장 빠른 방법은 바디 파서와 함께 Express.js 라이브러리를 사용하는 것입니다.
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.post("/pathpostdataissentto", function(request, response) {
console.log(request.body);
//Or
console.log(request.body.fieldName);
});
app.listen(8080);
이는 문자열에 대해 작동할 수 있지만 POST 데이터에 JSON 배열이 포함된 경우 대신 bodyParser.url 인코딩을 bodyParser.json으로 변경합니다.
더 많은 정보: http://www.kompulsa.com/how-to-accept-and-parse-post-requests-in-node-js/
Express v4.17.0
app.use(express.urlencoded( {extended: true} ))
console.log(req.body) // object
종속성이 전혀 없는 현대적인 비동기 방식의 Node.js 18:
server.mjs:
import { createServer } from 'node:http';
const rawReqToString = async (req) => {
const buffers = [];
for await(const chunk of req){
buffers.push(chunk);
}
return Buffer.concat(buffers).toString();
};
const server = createServer(async (req, res) => {
const object = JSON.parse(await rawReqToString(req));
...
});
server.listen(3000, 'localhost', () => {
console.log(`The server is running.`);
})
Express.js를 사용하는 경우 req.body에 액세스하기 전에 미들웨어 bodyParser를 추가해야 합니다.
app.use(express.bodyParser());
그럼 부탁할 수 있습니다.
req.body.user
JSON의 POST에서 데이터를 수신하는 경우.:
import http from 'http';
const hostname = '127.0.0.1';
const port = 3000;
const httpServer: http.Server = http.createServer((req: http.IncomingMessage, res:
http.ServerResponse) => {
if(req.method === 'POST') {
let body: string = '';
req.on('data',(chunck) => {
body += chunck;
});
req.on('end', () => {
const body = JSON.parse(body);
res.statusCode = 200;
res.end('OK post');
});
}
});
httpServer.listen(port, hostname, () => {
console.info(`Server started at port ${port}`);
})
그리고 Express와 같은 전체 프레임워크를 사용하고 싶지 않지만 업로드를 포함하여 다른 종류의 양식이 필요하다면 포르말린을 사용하는 것이 좋습니다.
express를 사용하지 않고 post 매개 변수를 추출할 수 있습니다.
1:nmp install multiparty
가져오기 . as 2: 가져니다옵파를티다중다▁2.var multiparty = require('multiparty');
3: `
if(req.method ==='POST'){
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
console.log(fields['userfile1'][0]);
});
}
4: 및 HTML FORM is.
<form method=POST enctype=multipart/form-data>
<input type=text name=userfile1><br>
<input type=submit>
</form>
이것이 당신에게 효과가 있기를 바랍니다.감사해요.
이를 달성하는 방법을 설명하는 비디오를 찾았습니다. https://www.youtube.com/watch?v=nuw48-u3Yrg
기본 "http" 모듈을 "querystring" 및 "stringbuilder" 모듈과 함께 사용합니다.응용 프로그램은 웹 페이지에서 두 개의 숫자(두 개의 텍스트 상자 사용)를 가져오고 제출 시 두 숫자의 합계(텍스트 상자의 값 유지)를 반환합니다.이것은 제가 다른 곳에서 찾을 수 있는 가장 좋은 예입니다.
관련 소스 코드:
var http = require("http");
var qs = require("querystring");
var StringBuilder = require("stringbuilder");
var port = 9000;
function getCalcHtml(req, resp, data) {
var sb = new StringBuilder({ newline: "\r\n" });
sb.appendLine("<html>");
sb.appendLine(" <body>");
sb.appendLine(" <form method='post'>");
sb.appendLine(" <table>");
sb.appendLine(" <tr>");
sb.appendLine(" <td>Enter First No: </td>");
if (data && data.txtFirstNo) {
sb.appendLine(" <td><input type='text' id='txtFirstNo' name='txtFirstNo' value='{0}'/></td>", data.txtFirstNo);
}
else {
sb.appendLine(" <td><input type='text' id='txtFirstNo' name='txtFirstNo' /></td>");
}
sb.appendLine(" </tr>");
sb.appendLine(" <tr>");
sb.appendLine(" <td>Enter Second No: </td>");
if (data && data.txtSecondNo) {
sb.appendLine(" <td><input type='text' id='txtSecondNo' name='txtSecondNo' value='{0}'/></td>", data.txtSecondNo);
}
else {
sb.appendLine(" <td><input type='text' id='txtSecondNo' name='txtSecondNo' /></td>");
}
sb.appendLine(" </tr>");
sb.appendLine(" <tr>");
sb.appendLine(" <td><input type='submit' value='Calculate' /></td>");
sb.appendLine(" </tr>");
if (data && data.txtFirstNo && data.txtSecondNo) {
var sum = parseInt(data.txtFirstNo) + parseInt(data.txtSecondNo);
sb.appendLine(" <tr>");
sb.appendLine(" <td>Sum: {0}</td>", sum);
sb.appendLine(" </tr>");
}
sb.appendLine(" </table>");
sb.appendLine(" </form>")
sb.appendLine(" </body>");
sb.appendLine("</html>");
sb.build(function (err, result) {
resp.write(result);
resp.end();
});
}
function getCalcForm(req, resp, data) {
resp.writeHead(200, { "Content-Type": "text/html" });
getCalcHtml(req, resp, data);
}
function getHome(req, resp) {
resp.writeHead(200, { "Content-Type": "text/html" });
resp.write("<html><html><head><title>Home</title></head><body>Want to some calculation? Click <a href='/calc'>here</a></body></html>");
resp.end();
}
function get404(req, resp) {
resp.writeHead(404, "Resource Not Found", { "Content-Type": "text/html" });
resp.write("<html><html><head><title>404</title></head><body>404: Resource not found. Go to <a href='/'>Home</a></body></html>");
resp.end();
}
function get405(req, resp) {
resp.writeHead(405, "Method not supported", { "Content-Type": "text/html" });
resp.write("<html><html><head><title>405</title></head><body>405: Method not supported</body></html>");
resp.end();
}
http.createServer(function (req, resp) {
switch (req.method) {
case "GET":
if (req.url === "/") {
getHome(req, resp);
}
else if (req.url === "/calc") {
getCalcForm(req, resp);
}
else {
get404(req, resp);
}
break;
case "POST":
if (req.url === "/calc") {
var reqBody = '';
req.on('data', function (data) {
reqBody += data;
if (reqBody.length > 1e7) { //10MB
resp.writeHead(413, 'Request Entity Too Large', { 'Content-Type': 'text/html' });
resp.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
}
});
req.on('end', function () {
var formData = qs.parse(reqBody);
getCalcForm(req, resp, formData);
});
}
else {
get404(req, resp);
}
break;
default:
get405(req, resp);
break;
}
}).listen(port);
다음과 같은 양식 필드
<input type="text" name="user[name]" value="MyName">
<input type="text" name="user[email]" value="myemail@somewherefarfar.com">
위의 답변 중 일부는 플랫 데이터만 지원하므로 실패합니다.
지금은 "querystring" 모듈 대신 "qs"로 Casey Chu 답변을 사용하고 있습니다.이것은 "바디 파서"가 사용하는 모듈이기도 합니다.따라서 중첩된 데이터를 원한다면 qs를 설치해야 합니다.
npm install qs --save
그런 다음 첫 번째 줄을 다음과 같이 바꿉니다.
//var qs = require('querystring');
var qs = require('qs');
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);
console.log(post.user.name); // should work
// use post['blah'], etc.
});
}
}
오버헤드를 인코딩하지 않고 원시 바이너리 POST 업로드를 사용하는 경우 다음을 사용할 수 있습니다.
클라이언트:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/api/upload", true);
var blob = new Uint8Array([65,72,79,74]); // or e.g. recorder.getBlob()
xhr.send(blob);
서버:
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.use (function(req, res, next) {
var data='';
req.setEncoding('binary');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
router.post('/api/upload', function(req, res, next) {
fs.writeFile("binaryFile.png", req.body, 'binary', function(err) {
res.send("Binary POST successful!");
});
});
이제 바디 파서가 내장된 익스프레스 미들웨어를 사용할 수 있습니다.즉, 다음만 수행하면 됩니다.
import express from 'express'
const app = express()
app.use(express.json())
app.post('/thing', (req, res) => {
console.log(req.body) // <-- this will access the body of the post
res.sendStatus(200)
})
해당 코드 예제는 Express 4.16.x가 설치된 ES6입니다.
노드 앱이 범람하지 않도록 POST 크기를 제한합니다.고속 및 연결에 모두 적합한 우수한 원시 모듈이 있어 크기와 길이에 따라 요청을 제한할 수 있습니다.
파일 업로드를 포함하는 경우 브라우저는 일반적으로 파일 업로드를 다음과 같이 보냅니다."multipart/form-data"내용 형식의이러한 경우 사용할 수 있습니다.
var multipart = require('multipart');
multipart.parse(req)
requ.body.body.body-parser에서 양식 데이터를 사용하려면 bodyParser()를 사용해야 합니다. 요청을 구문 분석하여 필요한 관련 정보를 쉽게 추출할 수 있는 형식으로 변환할 수 있습니다.
예를 들어, 프론트 엔드에 가입 양식이 있다고 가정해 보겠습니다.정보를 입력하고 서버에 세부 정보를 저장하도록 요청하는 중입니다.
본문 파서를 사용하는 경우 요청에서 사용자 이름과 암호를 추출하는 작업은 아래와 같이 간단합니다.
…………………………………………………….
var loginDetails = {
username : request.body.username,
password : request.body.password
};
사용에 대해 자세히 설명합니다.URLSearchParams:
- Node.js 지식:POST 데이터를 읽으려면 어떻게 해야 합니까?
- Node.js 설명서:클래스: URL 검색 매개 변수
- MDN: URL 검색 매개 변수
const http = require('http');
const POST_HTML =
'<html><head><title>Post Example</title></head>' +
'<body>' +
'<form method="post">' +
'Input 1: <input name="input1"><br>' +
'Input 2: <input name="input2"><br>' +
'Input 1: <input name="input1"><br>' +
'<input type="submit">' +
'</form>' +
'</body></html>';
const FORM_DATA = 'application/x-www-form-urlencoded';
function processFormData(body) {
const params = new URLSearchParams(body);
for ([name, value] of params.entries()) console.log(`${name}: ${value}`);
}
// req: http.IncomingMessage
// res: http.ServerResponse
//
function requestListener(req, res) {
const contentType = req.headers['content-type'];
let body = '';
const append = (chunk) => {
body += chunk;
};
const complete = () => {
if (contentType === FORM_DATA) processFormData(body);
res.writeHead(200);
res.end(POST_HTML);
};
req.on('data', append);
req.on('end', complete);
}
http.createServer(requestListener).listen(8080);
$ node index.js
input1: one
input2: two
input1: three
"Request - Simplified HTTP client" 및 Javascript Promise를 사용하여 POST 요청에 대한 응답을 쉽게 주고받을 수 있습니다.
var request = require('request');
function getData() {
var options = {
url: 'https://example.com',
headers: {
'Content-Type': 'application/json'
}
};
return new Promise(function (resolve, reject) {
var responseData;
var req = request.post(options, (err, res, body) => {
if (err) {
console.log(err);
reject(err);
} else {
console.log("Responce Data", JSON.parse(body));
responseData = body;
resolve(responseData);
}
});
});
}
언급URL : https://stackoverflow.com/questions/4295782/how-to-process-post-data-in-node-js
'programing' 카테고리의 다른 글
| SQL Server 데이터베이스에서 가장 큰 개체를 찾는 방법은 무엇입니까? (0) | 2023.05.22 |
|---|---|
| OpenMappedExe구성 대OpenExe 구성 (0) | 2023.05.22 |
| Express-js가 내 정적 파일을 가져올 수 없습니다. 왜죠? (0) | 2023.05.22 |
| 'Microsoft' 파일 또는 어셈블리를 로드할 수 없습니다.데이터.Edm' (0) | 2023.05.22 |
| 패키지 설치 방법.npm을 사용하는 현재 디렉터리의 json 종속성 (0) | 2023.05.22 |