node·进行Get请求
var http = require('http'); //通过require('http')获取node.js中原生的http模块 var url = require('url'); http.createServer(function(req, res) { res.writeHead(200, { //请求头 'Content-Type': 'text/plain;charset=utf-8' }); var Put = url.parse(req.url,true).query; //接收地址内容 //http://localhost:5200/?name=123&a=45&b=67 console.log(Put.name)//打印接收name console.log(Put.a)//打印接收a=45 console.log(Put.b)//打印接收b=67 res.write('我是小林'); //界面显示 res.end();//结束请求 }).listen(5200); //端口 console.log("运行了");
node·进行POST请求
var http = require('http'); //通过require('http')获取node.js中原生的http模块 var queryString = require('querystring'); http.createServer(function(req, res) {//固定格式 res.writeHead(200, { //请求头 'Content-Type': 'text/html;charset=utf-8' }); //http://localhost:5200/ if (req.method === 'POST') { //固定格式 //接受数据 let postData; req.on('data', chunk => {//接收请求时 postData += chunk.toString() }) req.on('end', () => {//结束请求时返回 console.log('postData:', postData)//打印看看接收请求时的内容 res.end('我是小林') }) } //res.end(); //Post结束请求不用写这里了,req.on里写了 }).listen(5200); //端口 console.log("运行了");
例子:
const express = require('express'); const bodyParser = require("body-parser");//body参数解析 const app = express(); app.use(bodyParser.urlencoded({ extended: false })); //application/x-www-form-urlencoded app.use(bodyParser.json()); // application/json /* 接口 */ app.get('/School', async (req, res) =>{//查询学校 let x = req.query; console.log("获取请求参数:",x) res.send(x) }) app.post('/Add', async (req, res) =>{//添加学校 let x = req.body; console.log("获取请求参数:",x) res.send(x) })
549 Views