跨域--跨域访问接口-整体说明 以及如何解决跨域问题

跨域问题是我们前端开发中经常会遇到的问题。通过此文档的了解,我们就能解决这类问题啦。

主要内容:

  • 素材准备
  • 错误原因分析
  • 用JSONP来解决
  • 用CORS来解决

跨域-素材准备及错误展示

目录结构

根目录
├── public
│   ├── js
    		└── axios.js
│   └── index.html  # 提前准备好的页面
└── server.js

前端页面

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <button id="btn1_get">接口测试1:get请求带参数</button>
    <button id="btn2_post"> 接口测试2:post-传递普通键值对</button>
    <hr/>
    <button id="btn3_postJSON">接口测试3:post-传递json</button>
    <hr/>
    <form id="myform">
        <input type="text" name="title">
        <input type="file" name="cover">
    </form>
    <button id="btn4_formdata">接口测试4:post-传递formdata</button>
    <hr/>
    <script src="./js/axios.js"></script>
    <script>
    document.getElementById('btn1_get').addEventListener('click',() => {
        axios.get('http://localhost:3000/getapi', {params: {a:1,b:2}})
    })
    var obj = {
        "name":"abc",
        "address":{
            "a":1,
            "b":2,
            "info":"c"
        }
    }
    document.getElementById('btn2_post').addEventListener('click', () => {
        const params = new URLSearchParams();
        params.append('param1', 'value1');
        params.append('param2', 'value2');
        axios.post('http://localhost:3000/post', params, {
            headers: {"content-type":"application/x-www-form-urlencoded"}})
    })

    document.getElementById('btn3_postJSON').addEventListener('click', () => {
        axios.post('http://localhost:3000/postJSON', obj)
    })

    document.getElementById('btn4_formdata').addEventListener('click', () => {
        console.log(1)
        var fd = new FormData(document.getElementById('myform'));

        axios.post('http://localhost:3000/publish', 
            fd
        )
    })
    </script>
</body>
</html>

后端

// 实现get接口
const express = require('express')
const app = express();

app.use(express.static('public'))
// 引入bodyParse包
const bodyParser = require('body-parser')
// 使用包. 则在后续的post请求中
// 会自动加入req.body属性,这个属性中就包含了post请求所传入的参数
// 处理普通的键值对格式
// Content-Type: application/x-www-form-urlencoded
app.use(express.urlencoded())

// 处理JSON格式
// Content-Type: application/json;
app.use(express.json())

// 引入multer包
const multer = require('multer');

// 配置一下multer
// 如果本次post请求涉及文件上传,则上传到uploads这个文件夹下
// Content-Type: multipart/form-data;
var upload = multer({ dest: 'uploads/'})


// 实现接口1: get类型接口
// 返回所传入的参数,并附上上时间戳
app.get('/getapi',(req,res)=>{
    // 通过 req.query快速获取传入的参数
    console.log(req.query);
    le
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值