nodejs 杂记
后端代码:
const http = require('http');
const url = require('url');
const querystring = require('querystring');
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
const corsHeaders = {
'Access-Control-Allow-Origin': '*', // 或者指定特定的域名
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
};
let queryParams;
if (request.method === 'GET') {
// 解析请求,包括路径名和查询参数
const parsedUrl = url.parse(request.url);
// 解析查询参数
queryParams = querystring.parse(parsedUrl.query);
console.log(parsedUrl, queryParams)
}
if (request.method === 'POST') {
let body = '';
request.on('data', chunk => {
body += chunk.toString(); // 转换为字符串
});
request.on('end', () => {
const params = querystring.parse(body); // 解析参数
console.log(params); // 输出参数
response.writeHead(200, corsHeaders);
// 发送响应数据 "Hello World"
const data = {
code: 'AAAAAAA',
msg: '',
data: {
id: '1',
name: 'dsa'
}
}
response.end(JSON.stringify(data));
});
}
// if (queryParams.id == 3) {
// response.writeHead(200, corsHeaders);
// // 发送响应数据 "Hello World"
// const data = {
// code: 'AAAAAAA',
// msg: '',
// data: {
// id: '1',
// name: 'dsa'
// }
// }
// response.end(JSON.stringify(data));
// } else {
// response.writeHead(500, corsHeaders);
// // 发送响应数据 "Hello World"
// const data = {
// code: 'ERROR',
// msg: 'uuu',
// data: null
// }
// response.end(JSON.stringify(data));
// }
}).listen(8888);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
前端代码:
// get
var xhr = new XMLHttpRequest();
xhr.open("post", "http://localhost:8888?id=47&name=kl", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json); // 处理返回的数据
}
};
xhr.send();
// post
// var xhr = new XMLHttpRequest();
// xhr.open("POST", "http://localhost:8888", true);
// xhr.onreadystatechange = function () {
// if (xhr.readyState == 4 && xhr.status == 200) {
// var json = JSON.parse(xhr.responseText);
// console.log(json); // 处理返回的数据
// }
// };
// let form = new FormData()
// form.append('id', '3')
// xhr.send(form);

浙公网安备 33010602011771号