get请求:
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模拟提交表单请求</title>
</head>
<body>
<input type="text" id="username"/>
<input type="password" id="password"/>
<input type="button" value="提交" id="button">
<script>
//获取按钮元素
let btn = document.getElementById('button');
//获取姓名文本框
let username = document.getElementById('username');
//获取年龄文本框
let password = document.getElementById('password');
//为按钮添加点击事件
btn.onclick = function () {
//创建ajax实例化对象
let xhr = new XMLHttpRequest();
//获取用户在文本框中输入的值
let nameVal = username.value;
let passwordVal = password.value;
let params = 'username=' + nameVal + '&password=' + passwordVal;
//配置ajax对象
xhr.open('get', 'http://localhost:3000/get?' + params);
//发送请求
xhr.send();
//获取服务器端响应的数据
xhr.onload = function () {
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
node.js部分:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/get', (req, res) => {
//req.query 获取前端传来的参数
res.send(req.query)
})
app.listen(3000);
console.log('服务器运行成功');
首先我们需要先用node运行node.js代码,运行完之后前端部分才可以获取到文本框输入的内容并把内容发送到后台,当后台接收到前端传过来的参数之后,再通过res.send返回给前端,前端再控制台中打印服务器响应的数据。
post请求:
post请求需要把参数写到send方法里面,而且必须加上请求头。
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模拟提交表单请求</title>
</head>
<body>
<input type="text" id="username"/>
<input type="password" id="password"/>
<input type="button" value="提交" id="button">
<script>
//获取按钮元素
let btn = document.getElementById('button');
//获取姓名文本框
let username = document.getElementById('username');
//获取年龄文本框
let password = document.getElementById('password');
//为按钮添加点击事件
btn.onclick = function () {
//创建ajax实例化对象
let xhr = new XMLHttpRequest();
//获取用户在文本框中输入的值
let nameVal = username.value;
let passwordVal = password.value;
let params = 'username=' + nameVal + '&password=' + passwordVal;
//配置ajax对象
xhr.open('post', 'http://localhost:3000/post');
//设置请求参数格式的类型(post请求必须要设置,get不需要设置)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//发送请求
xhr.send(params);
//获取服务器端响应的数据
xhr.onload = function () {
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
node.js部分:post请求依赖第三方插件body-parser
const express = require('express');
const path = require('path');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded())
app.use(express.static(path.join(__dirname, 'public')));
app.post('/post', (req, res) => {
console.log(req.body);
res.send(req.body)
})
app.listen(3000);
console.log('服务器运行成功');