Jak uzyskać zmienne GET (query string) w Expressie.js na węźle.js?
Czy możemy pobrać zmienne w łańcuchu zapytania w Node.js tak jak w $_GET
w PHP?
Wiem, że w Node.js możemy uzyskać adres URL w żądaniu. Czy istnieje metoda, aby uzyskać parametry ciągu zapytania?
20 answers
Yes you can access req.adres url i wbudowany Moduł url
na adres url .parse to ręcznie:
var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
Jednak w expressjs jest to już zrobione za Ciebie i możesz po prostu użyć req.zapytanie {[5] } dla tego:
var id = req.query.id; // $_GET["id"]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-29 04:10:40
Odkąd wspomniałeś o Expressie.js w Twoich tagach, oto odpowiedź ekspresowa: Użyj req.query . Np.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('id: ' + req.query.id);
});
app.listen(3000);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-30 11:24:07
W Expressie użyj req.query
.
req.params
pobiera tylko parametry trasy, a nie parametry ciągu zapytania. Zobacz express lub żagle dokumentacja:
(req.params) sprawdza params trasy, np.:/user/: id
(req.query) sprawdza ciąg zapytania params, np:?id=124766]}
(req.body), ex: id = 12 to use urlencoded request bodies, req.ciało powinno być przedmiotem. Można to zrobić za pomocą _express.bodyParser middleware.
To powiedziawszy, przez większość czasu chcesz uzyskać wartość parametru niezależnie od jego źródła. W takim przypadku użyj req.param('foo')
.
Wartość parametru zostanie zwrócona niezależnie od tego, czy zmienna znajdowała się w parametrach trasy, łańcuchu zapytania, czy w zakodowanej treści żądania.
Uwaga na marginesie - jeśli chcesz uzyskać przecięcie wszystkich trzech typów parametrów żądania (podobnych do PHP $_REQUEST
), wystarczy połączyć parametry razem - oto jak ustaw go w żaglach . Należy pamiętać, że obiekt path/route parameters (req.params
) ma właściwości tablicy, więc kolejność ma znaczenie (chociaż ta może się zmienić w Express 4)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-10 03:28:19
Na Ekspres.js chcesz zrobić req.params
:
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 12:03:11
Nauczyłem się z innych odpowiedzi i postanowiłem użyć tego kodu w całej mojej stronie:
var query = require('url').parse(req.url,true).query;
Wtedy możesz po prostu zadzwonić
var id = query.id;
var option = query.option;
Gdzie URL do get powinien być
/path/filename?id=123&option=456
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 12:05:12
Powinieneś być w stanie zrobić coś takiego:
var http = require('http');
var url = require('url');
http.createServer(function(req,res){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query); //{Object}
res.end("End")
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-29 18:20:32
//get query¶ms in express
//etc. example.com/user/000000?sex=female
app.get('/user/:id', function(req, res) {
const query = req.query;// query = {sex:"female"}
const params = req.params; //params = {id:"000000"}
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-15 02:37:11
Istnieją 2 sposoby przekazywania parametrów za pomocą metody GET
Metoda 1 :
Podejście MVC, w którym przekazujesz parametry takie jak / routename/: paramname
W takim przypadku możesz użyć req.params.paramname aby uzyskać wartość parametru, na przykład zapoznaj się z poniższym kodem, w którym oczekuję Id jako param
link może być taki : http://myhost.com/items/23
var express = require('express');
var app = express();
app.get("items/:id",function(req,res){
var id = req.params.id;
//further operations to perform
});
app.listen(3000);
Metoda 2 :
Podejście ogólne: przekazywanie zmiennych jako ciąg zapytania za pomocą '?"operator
Na przykład patrz poniżej kod gdzie oczekuję Id jako parametru zapytania
link może być taki : http://myhost.com/items?id=23
var express = require('express');
var app = express();
app.get("/items",function(req,res){
var id = req.query.id;
//further operations to perform
});
app.listen(3000);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-26 07:33:23
Aktualizacja 4 maja 2014
Stara odpowiedź zachowana tutaj: https://gist.github.com/stefek99/b10ed037d2a4a323d638
1) Install express: npm install express
App.js
var express = require('express');
var app = express();
app.get('/endpoint', function(request, response) {
var id = request.query.id;
response.end("I have received the ID: " + id);
});
app.listen(3000);
console.log("node express app started at http://localhost:3000");
2) Uruchom aplikację: node app.js
3) Odwiedź w przeglądarce: http://localhost:3000/endpoint?id=something
Otrzymałem ID: coś
(wiele rzeczy się zmieniło od czasu mojej odpowiedzi i uważam, że warto być na bieżąco)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-04 01:36:11
Jeśli używasz ES6 i Express , spróbuj tegodestrukcji podejście:
const {id, since, fields, anotherField} = request.query;
W kontekście:
const express = require('express');
const app = express();
app.get('/', function(req, res){
const {id, since, fields, anotherField} = req.query;
});
app.listen(3000);
Możesz użyć wartości domyślnych z destructuring
, too
// sample request for testing
const req = {
query: {
id: '123',
fields: ['a', 'b', 'c']
}
}
const {
id,
since = new Date().toString(),
fields = ['x'],
anotherField = 'default'
} = req.query;
console.log(id, since, fields, anotherField)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-20 22:20:19
Mały węzeł.serwer HTTP js nasłuchujący na porcie 9080, parsujący dane GET lub POST i wysyłający je z powrotem do Klienta w ramach odpowiedzi to:
var sys = require('sys'),
url = require('url'),
http = require('http'),
qs = require('querystring');
var server = http.createServer(
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end',function() {
var POST = qs.parse(body);
//console.log(POST);
response.writeHead( 200 );
response.write( JSON.stringify( POST ) );
response.end();
});
}
else if(request.method == 'GET') {
var url_parts = url.parse(request.url,true);
//console.log(url_parts.query);
response.writeHead( 200 );
response.write( JSON.stringify( url_parts.query ) );
response.end();
}
}
);
server.listen(9080);
Zapisz go jako parse.js
i uruchom go w konsoli, wpisując " node parse.js".
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 12:15:30
Whitequark ładnie zareagował. Ale z aktualnymi wersjami Node.js i Express.js wymaga jeszcze jednej linii. Upewnij się, że dodałeś "wymagaj http" (druga linia). Zamieściłem tutaj pełniejszy przykład, który pokazuje, jak to połączenie może działać. Po uruchomieniu wpisz http://localhost:8080/?name=abel&fruit=apple
w przeglądarce, a otrzymasz fajną odpowiedź na podstawie kodu.
var express = require('express');
var http = require('http');
var app = express();
app.configure(function(){
app.set('port', 8080);
});
app.get('/', function(req, res){
res.writeHead(200, {'content-type': 'text/plain'});
res.write('name: ' + req.query.name + '\n');
res.write('fruit: ' + req.query.fruit + '\n');
res.write('query: ' + req.query + '\n');
queryStuff = JSON.stringify(req.query);
res.end('That\'s all folks' + '\n' + queryStuff);
});
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 16:29:52
To takie proste:
Przykładowy URL:
http://stackoverflow.com:3000/activate_accountid=3&activatekey=$2a$08$jvGevXUOvYxKsiBt.PpMs.zgzD4C/wwTsvjzfUrqLrgS3zXJVfVRK
Możesz wydrukować wszystkie wartości łańcucha zapytania za pomocą:
console.log("All query strings: " + JSON.stringify(req.query));
Wyjście
Wszystkie ciągi zapytań: {"id": "3","activatekey": "$2A$08$jvGevXUOvYxKsiBt.PpMs.zgzD4C / wwTsvjz fUrqLrgS3zXJVfVRK"}
Aby wydrukować konkretne:
console.log("activatekey: " + req.query.activatekey);
Wyjście
Activatekey: $2A$08$jvGevXUOvYxKsiBt.PpMs.zgzD4C / wwTsvjzfUrqLrgS3zXJVfVRK
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 14:54:12
Możesz użyć
request.query.<varible-name>;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-07 08:22:07
Możesz użyć z express ^4.15.4:
var express = require('express'),
router = express.Router();
router.get('/', function (req, res, next) {
console.log(req.query);
});
Mam nadzieję, że to pomoże.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-27 06:57:44
app.get('/user/:id', function(req, res) {
res.send('user' + req.params.id);
});
Możesz użyć tego lub wypróbować body-parser do parsowania elementu specjalnego z parametrów żądania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-31 18:41:02
W express.js
możesz uzyskać to całkiem łatwo, wszystko, co musisz zrobić w funkcji kontrolera to:
app.get('/', (req, res, next) => {
const {id} = req.query;
// rest of your code here...
})
I to wszystko, zakładając, że używasz składni es6.
PD. {id}
oznacza Object destructuring
, nową funkcję es6.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-18 23:24:28
Możesz użyć modułu url do zbierania parametrów za pomocą url.parse
var url = require('url');
var url_data = url.parse(request.url, true);
var query = url_data.query;
W expressjs robi się to przez,
var id = req.query.id;
Eg:
var express = require('express');
var app = express();
app.get('/login', function (req, res, next) {
console.log(req.query);
console.log(req.query.id); //Give parameter id
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-05 04:27:27
Używam MEANJS 0.6.0 z [email protected], jest dobre
Klient:
Kontroler:
var input = { keyword: vm.keyword };
ProductAPi.getOrder(input)
Usługi:
this.getOrder = function (input) {return $http.get('/api/order', { params: input });};
Serwer
Trasy
app.route('/api/order').get(products.order);
Controller
exports.order = function (req, res) {
var keyword = req.query.keyword
...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-10 06:02:37
Możesz użyć req.params with ExpressJS
router.get('/recipe/:id', function (req, res, next) {
database.sendQuery("SELECT * FROM recipe WHERE id = " + req.params.id , function (err, results) {
if (err) {
console.log(err)
} else {
res.json(results)
}
})
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-11 14:34:44