引用
前面学习了http模块这里使用原生的http模块进行开发一个api接口服务器作为练习,由于这里还没有学到数据库这里会使用json文件作为数据存储也间接联系fs模块。
一、创建服务
const http = require('http');
const server = http.createServer((req, res) => {
});
// 监听3000端口
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
二、准备json数据
{
"name":"Anlijun",
"info":{
"age":18,
"sex":"男"
},
"hobbies":["吃饭","睡觉","打豆豆"]
}
目录结构大概是这样
三、书写路由
get方法
// 根据不同的 URL 和方法进行路由处理
if (method === 'GET') {
if (url === '/getName') {
try {
const data = fs.readFileSync(path.join(__dirname, 'data.json'), 'utf-8')
const jsonData = JSON.parse(data)
res.statusCode = 200;
res.end(jsonData.name);
} catch (error) {
console.log(error)
res.statusCode = 500;
res.end('Internal Server Error');
}
}
}
发个ajax试一下
创建测试用的html
XHR不解释了
<script>
document.getElementById('getFun').addEventListener('click', function () {
// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();
// 打开一个 GET 请求,这里以请求一个 JSON 数据为例,你可以替换成实际的 API 地址
xhr.open('GET', 'http://127.0.0.1:3000/getName', true);
// 设置请求状态变化的回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 请求成功,解析响应数据
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = `Body: ${xhr.responseText}`;
} else {
// 请求失败,输出错误信息
console.error('Request failed. Status:', xhr.status);
}
}
};
// 发送请求
xhr.send();
});
</script>
启动服务
打开网页点击请求
然后就看到了很熟悉的错误跨域了,
nodejs解决跨域
// 设置允许跨域的域名,这里使用 * 表示允许所有域名跨域
res.setHeader('Access-Control-Allow-Origin', '*');
// 设置允许的请求方法
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// 设置允许的请求头
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
重启服务再试一遍
这里你已经成功了。
再来一个post请求
if (req.method === 'OPTIONS') {
// 如果是 OPTIONS 请求,返回 204 状态码表示请求已处理但无内容返回
res.writeHead(204);
res.end();
}
if (method === 'POST' && req.headers['content-type'] === 'application/json') {
if (url === '/setName') {
// 处理 POST 请求的数据
console.log('1111111111111');
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
const data = fs.readFileSync(path.join(__dirname, 'data.json'), 'utf-8')
const jsonData = JSON.parse(data)
jsonData.name =JSON.parse(body).name
console.log(body);
fs.writeFileSync(path.join(__dirname, 'data.json'), JSON.stringify(jsonData))
res.statusCode = 200;
res.end('success');
}
catch (error) {
console.log(error)
res.statusCode = 500;
res.end('Internal Server Error');
}
})
}
}
发个ajax试一下
const input = document.querySelector('input')
const value = input.value
// 创建 XMLHttpRequest 对象
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('name', value);
xhr.open('POST', 'http://127.0.0.1:3000/setName', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// 设置请求状态变化的回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// 请求成功,解析响应数据
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = `Body: ${xhr.responseText}`;
} else {
// 请求失败,输出错误信息
console.error('Request failed. Status:', xhr.status);
}
}
};
// 发送请求
xhr.send(formData);
});
数据页更改成功了