帮我写一个基于http模块和ajax可以前后端互传数据的代码
时间: 2023-04-02 19:01:05 浏览: 104
好的,以下是一个基于http模块和ajax可以前后端互传数据的代码示例:
前端代码:
```
<!DOCTYPE html>
<html>
<head>
<title>AJAX Demo</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>AJAX Demo</h1>
<input type="text" id="input">
<button id="send">发送</button>
<div id="output"></div>
<script>
$(function() {
$('#send').click(function() {
var data = $('#input').val();
$.ajax({
url: '/api',
type: 'POST',
data: {data: data},
success: function(res) {
$('#output').text(res);
},
error: function(err) {
console.log(err);
}
});
});
});
</script>
</body>
</html>
```
后端代码:
```
const http = require('http');
const url = require('url');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
const method = req.method;
const urlObj = url.parse(req.url);
const path = urlObj.pathname;
const query = querystring.parse(urlObj.query);
if (method === 'POST' && path === '/api') {
let postData = '';
req.on('data', chunk => {
postData += chunk.toString();
});
req.on('end', () => {
const data = querystring.parse(postData);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data.data);
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('404 Not Found');
}
});
server.listen(300, () => {
console.log('Server is running at http://localhost:300');
});
```
这个代码示例可以实现前后端互传数据,前端通过ajax发送POST请求,后端接收请求并返回数据。
阅读全文