接口跨域问题:前面的POST和GET接口,存在一个不支持跨域问题
使用在线版本的jqueryStaticfile CDN
https://www.staticfile.org/

HTML+jquery ————>在这里的时候需要启动服务器
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- <script src="https://cdn.staticfile.org/jquery/3.6.1/jquery.min.js">script>
- head>
- <body>
- <button id="get">GETbutton>
- <button id="post">POSTbutton>
- <script>
- $(document).ready(function(){
- //1.测试GET接口
- $('#get').on('click',function(){
- $.ajax({
- type:'GET',//规定请求的类型(GET 或 POST)。
- url:'http://127.0.0.1/api/get',//规定发送请求的 URL
- data:{name:'zs',age:20},//规定要发送到服务器的数据。
- success:function(res){
- console.log(res)
- },
-
- })
- })
- //2.测试POST接口
- $('#post').on('click',function(){
- $.ajax({
- type:'POST',
- url:'http://127.0.0.1/api/post',
- data:{name:'白居易',age:80},
- success:function(res){
- console.log(res)
- },
-
- })
-
- })
- })
- script>
- body>
- html>
from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.————————————说明接口存在跨域的问题
当前协议是file,然后请求发送的url是http协议————只要协议、域名、端口号任何一个不同即不行
解决跨域问题的主要方案是两种:
CORS(主流方案,推荐使用)
JSONP(有缺陷的解决方案:只支持GET请求)-——-
——或者直接设置响应头
CORS是Express的第三方中间件。通过安装和配置cors中间件,可以解决跨域问题
运行:
创建api路由
- //导入express
- const express=require('express')
- //创建路由对象
- const Router=express.Router()
- //定义get接口
- Router.get('/get',(req,res)=>{
- //通过req.query获取客户端通过查询字符串获取发送到服务器的数据
- const query=req.query //get请求使用req.query post请求使用req.body
- res.send(//服务器的响应
- {
- status:0,//0表示处理成功 1表示处理失败
- msg:'GET 请求成功!',//状态的描述
- data:query //响应给客户端的数据
-
- }
- )
- })
- //定义post接口
- Router.post('/post',(req,res)=>{
- //通过req.query获取客户端通过查询字符串获取发送到服务器的数据
- const body=req.body //get请求使用req.query post请求使用req.body
- res.send(//服务器的响应
- {
- status:0,//0表示处理成功 1表示处理失败
- msg:'POST 请求成功!',//状态的描述
- data:body //响应给客户端的数据
-
- }
- )
- })
- //向外导出路由
- module.exports=Router//之前={对象 对象里面是属性 可以做一个省略}
创建服务器
- const express=require('express')
- //创建服务器
- const app=express()
- //配置解析表单数据的中间件
-
- app.use(express.urlencoded({extended:false}))
- const cors=require('cors')
- app.use(cors())
- //导入路由模块
- const router=require('./api路由模块')
- //把路由模块注册到app上 ——app.use作用注册全局中间件
- app.use('/api',router)//请求到达服务器 需要进行中间件的处理--挨个进行路由的匹配_统一前缀
-
-
- app.listen(80,()=>{
- console.log('express服务器启动成功 127.0.0.1')
- })
