HTTP
Server 程式範例
const http = require('http');
http.createServer(function (request, response){
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3000);
console.log('Server running on port 3000.');Request 程式範例
以下也為解析 big5 網頁範例,記得使用 buffer 讀取,然後用 iconv 轉格式
const http = require("http");
const iconv = require("iconv-lite");
const querystring = require("querystring");
const requestBody = {
PG2: " 6 ",
PgNo: 6,
s: 0,
};
const postData = querystring.stringify(requestBody);
const options = {
hostname: "lotto.bestshop.com.tw",
path: "/649/where.asp",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(postData),
},
};
// 因為是要存 buffer 必須用 array
const result = [];
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.on("data", (chunk) => {
result.push(chunk);
});
res.on("end", () => {
const resp = iconv.decode(Buffer.concat(result), "big5");
console.log(resp);
console.log("No more data in response.");
});
});
req.on("error", (e) => {
console.error(`problem with request: ${e.message}`);
});
req.write(postData);
req.end();純 Node.js 接收 POST request
包含路由與讀取Body
因為 POST request 會先有一個 options 請求,所以要先回覆
讀檔案
讀HTML
寫檔案Request與讀檔案Server
Server.js
client.js
靜態Server
#取得remote ip
如果沒有proxy可用req.socket.remoteAddress 但如果有proxy的話req.socket.remoteAddress
用瀏覽器發送請求如果server沒有在nginx的proxy後面會取不到x-forwarded-for
注意 如果是在proxy後面 例如nginx
會出現如下
必須在nginx config加上
之後即會出現 x-forwarded-for的ip
如果我們把上面的x-forwarded-for請求spoof
改為其他IP
之後nginx的x forwarded會出現如下
第一個是我們spoof的位置 第二個是原本client的真實ip
也可用如下測試(spoof一個x-forwarded-for)
不錯的文章
https://imququ.com/post/x-forwarded-for-header-in-http.html
寫一個Proxy Server
接收到請求後可以進行轉發,可用來避開cors
發送Requst記得加上Header content type
Last updated
Was this helpful?