БАЗОВЫЙ HTTP
- Получить URL заголовка и методы запроса в консоли:
const http = require(‘http’); const server = http.createServer((req,res) => { const { headers,url,method } = req; console.log(headers,url,method); res.end(); }); const PORT = 5000; server.listen(PORT,() => console.log(`server running on port ${PORT}`));
В запросе вы можете отправить запрос любого типа в почтальоне, например. http://localhost:5000/dfdfdf
с помощью get o post и результат будет на консоли
2. Установите любой пакет в качестве зависимости от среды разработки:
npm install -D package-name
3. Ответ с данными JSON
const http = require('http'); const todos = [ { id: 1, text: 'Todo One' }, { id: 2, text: 'Todo two' }, { id: 3, text: 'Todo three' }, ]; const server = http.createServer((req, res) => { res.setHeader('Content-type', 'application/json'); res.setHeader('X-Powered-By', 'Node.js'); //res.write("<h2>hello</h2>"); use text/html to view in html res.end( JSON.stringify({ success: true, data: todos, }) ); }); const PORT = 5000; server.listen(PORT, () => console.log(`server running on port ${PORT}`));
4. Отправка кодов состояния
const http = require('http'); const todos = [ { id: 1, text: 'Todo One' }, { id: 2, text: 'Todo two' }, { id: 3, text: 'Todo three' }, ]; const server = http.createServer((req, res) => { res.writeHead(401, { 'Content-Type': 'application/json', 'X-powered-by': 'Node.js', }); res.end( JSON.stringify({ success: false, error: 'some error', data: null, }) ); }); const PORT = 5000; server.listen(PORT, () => console.log(`server running on port ${PORT}`));
5. Отправка данных на сервер
предположим, что мы отправляем необработанные данные json как
{
«текст» : «что сделать четыре»
}
тогда код o/p в консоли
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(401, { 'Content-Type': 'application/json', 'X-powered-by': 'Node.js', }); //getting data from headers //console.log(req.headers.authorization); //getting data from body let body = []; req.on('data',chunk => { body.push(chunk); }).on('end',() => { body = Buffer.concat(body).toString(); console.log(body); }); res.end( JSON.stringify({ success: false, error: 'some error', data: null, }) ); }); const PORT = 5000; server.listen(PORT, () => console.log(`server running on port ${PORT}`));
6. GET/POST для определенного URL
что, если теперь мы хотим отправить запрос GET и POST на определенный URL-адрес
отправить запрос GET на /todos
POST на /todos и отправить в теле необработанный json как
{
“id” : 4,
«текст» : «что сделать четыре»
}
const http = require('http'); const todos = [ { id: 1, text: 'Todo One' }, { id: 2, text: 'Todo two' }, { id: 3, text: 'Todo three' }, ]; const server = http.createServer((req, res) => { const { method, url } = req; let body = []; req .on('data', (chunk) => { body.push(chunk); }) .on('end', () => { body = Buffer.concat(body).toString(); let status = 404; const response = { success: false, data: null, error: null, }; if (method == 'GET' && url == '/todos') { status = 200; response.success = true; response.data = todos; } else if (method == 'POST' && url == '/todos') { const { id, text } = JSON.parse(body); if (!id || !text) { status = 400; response.error = 'id or text not found'; } else { todos.push({ id, text }); status = 201; response.success = true; response.data = todos; } } res.writeHead(status, { 'Content-Type': 'application/json', 'X-powered-by': 'Node.js', }); res.end(JSON.stringify(response)); }); }); const PORT = 5000; server.listen(PORT, () => console.log(`server running on port ${PORT}`));