创建一个文件夹,在该文件夹中创建index.html
文件,该文件中的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
window.onload = function () {
var btn = document.getElementById('btnLogin')
btn.addEventListener('click', function () {
sendRequest()
})
function sendRequest() {
var userName = document.getElementById('userName').value
var xhr = new XMLHttpRequest()
let url = 'http://localhost:8080/getUserInfo?userName=' + userName
xhr.open('get', url, true)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText)
}
}
}
}
</script>
</head>
<body>
用户名:<input type="text" id="userName" /> <br />
<button id="btnLogin">登录</button>
</body>
</html>
在该文件夹下面安装express:
npm install express
同时创建server.js
文件,该文件的代码如下:
var express = require('express')
var app = express()
app.get('/getUserInfo/', function (req, res) {
var userName = req.query.userName
var data = {
id: 1,
userName: userName,
gender: '男',
}
// var result = JSON.stringify(data)
// res.writeHead(200, { 'Content-Type': 'application/json' })
// res.write(result)
// res.end()
res.send(data)
})
app.listen(8080, function () {
console.log('服务器启动')
})
下面启动服务端
同时index.html
文件也通过vscode
自带的服务器进行访问。
这时会出现如下错误:
Access to XMLHttpRequest at 'http://localhost:8080/getUserNameInfo?name=admin' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
通过以上错误可以发现,现在的程序出现跨域的问题,
下面看一下具体的解决方案: CORS,express中使用CORS的解决方案有2种,
CORS只需要向响应头header中注入Access-Control-Allow-Origin
,这样浏览器检测到header中的Access-Control-Allow-Origin
,则就可以跨域操作了(同源策略不生效)。
Cross-Site Resource Sharing : 跨域资源共享。
1、直接引入cors,解决跨域问题
var express = require('express')
var app = express()
var cors = express('cors')
app.use(cors)
app.get('/getUserInfo/', function (req, res) {
var userName = req.query.userName
var data = {
id: 1,
userName: userName,
gender: '男',
}
// 需要设置响应头
res.setHeader('Access-Control-Allow-Origin', '*')
// var result = JSON.stringify(data)
// res.writeHead(200, { 'Content-Type': 'application/json' })
// res.write(result)
// res.end()
res.send(data)
})
app.listen(8080, function () {
console.log('服务器启动')
})
2、直接设置响应头,接收跨域请求的处理
var express = require('express')
var app = express()
// `CORS`主要的实现方式是服务端通过对响应头的设置,接收跨域请求的处理。
app.all('*', function (req, res) {
res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:5500')
res.header('Access-Control-Allow-Methods', 'GEt,POST,PUT')
res.header('Access-Control-Allow-Headers', 'Content-Type')
res.header('Content-Type', 'application/json;charset=utf-8')
req.next()
})
app.get('/getUserInfo/', function (req, res) {
var userName = req.query.userName
var data = {
id: 1,
userName: userName,
gender: '男',
}
// var result = JSON.stringify(data)
// res.writeHead(200, { 'Content-Type': 'application/json' })
// res.write(result)
// res.end()
res.send(data)
})
app.listen(8080, function () {
console.log('服务器启动')
})
结果: