Dalam contoh "Hello World" ini:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
Bagaimana saya bisa mendapatkan parameter dari string kueri?
http://127.0.0.1:8000/status?name=ryan
Dalam dokumentasinya, mereka menyebutkan:
node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan'
, search: '?name=ryan'
, query: { name: 'ryan' }
, pathname: '/status'
}
Tapi saya tidak mengerti bagaimana cara menggunakannya. Adakah yang bisa menjelaskan?
[t]he request object is an instance of IncomingMessage
, dan ituhttp.IncomingMessage
memiliki propertiurl
.Ada juga modul QueryString 's
parse()
metode:var http = require('http'), queryString = require('querystring'); http.createServer(function (oRequest, oResponse) { var oQueryParams; // get query params as object if (oRequest.url.indexOf('?') >= 0) { oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, '')); // do stuff console.log(oQueryParams); } oResponse.writeHead(200, {'Content-Type': 'text/plain'}); oResponse.end('Hello world.'); }).listen(1337, '127.0.0.1');
sumber
require('url').parse('/status?name=ryan', {parseQueryString: true}).query
kembali
{ name: 'ryan' }
ref: https://nodejs.org/api/url.html#url_urlobject_query
sumber
node -v
v9.10.1Jika Anda mencoba untuk konsol objek kueri log secara langsung, Anda akan mendapatkan kesalahan
TypeError: Cannot convert object to primitive value
Jadi saya akan menyarankan penggunaan
JSON.stringify
const http = require('http'); const url = require('url'); const server = http.createServer((req, res) => { const parsedUrl = url.parse(req.url, true); const path = parsedUrl.pathname, query = parsedUrl.query; const method = req.method; res.end("hello world\n"); console.log(`Request received on: ${path} + method: ${method} + query: ${JSON.stringify(query)}`); console.log('query: ', query); }); server.listen(3000, () => console.log("Server running at port 3000"));
Jadi melakukan
curl http://localhost:3000/foo\?fizz\=buzz
akan kembaliRequest received on: /foo + method: GET + query: {"fizz":"buzz"}
sumber
Dimulai dengan Node.js 11, url.parse dan metode lain dari API URL Lawas tidak digunakan lagi (hanya dalam dokumentasi, pada awalnya) dan mendukung API URL WHATWG standar . API baru tidak menawarkan penguraian string kueri menjadi objek. Itu bisa dicapai dengan menggunakan metode tthe querystring.parse :
// Load modules to create an http server, parse a URL and parse a URL query. const http = require('http'); const { URL } = require('url'); const { parse: parseQuery } = require('querystring'); // Provide the origin for relative URLs sent to Node.js requests. const serverOrigin = 'http://localhost:8000'; // Configure our HTTP server to respond to all requests with a greeting. const server = http.createServer((request, response) => { // Parse the request URL. Relative URLs require an origin explicitly. const url = new URL(request.url, serverOrigin); // Parse the URL query. The leading '?' has to be removed before this. const query = parseQuery(url.search.substr(1)); response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end(`Hello, ${query.name}!\n`); }); // Listen on port 8000, IP defaults to 127.0.0.1. server.listen(8000); // Print a friendly message on the terminal. console.log(`Server running at ${serverOrigin}/`);
Jika Anda menjalankan script di atas, Anda dapat menguji respon server seperti ini, misalnya:
sumber