Node--Vue--解决跨域问题

本文详细解释了浏览器的同源策略导致的跨域问题,包括不同情况下的跨域示例,如主域名、子域名、端口和协议的差异。同时提供了前端Vue和后端Node的代码示例,展示如何通过设置CORS来解决跨域访问限制。
  1. 什么是跨域?
    跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。
    同源就是指,域名、协议、端口均为相同。
    例如:
    http://www.111.com/index.html 调用 http://www.111.com/server.php
    (非跨域)
    http://www.111.com/index.html 调用 http://www.222.com/server.php
    (主域名不同:111与222不同,跨域)
    http://aaa.111.com/index.html 调用 http://bbb.111.com/server.php
    (子域名不同:aaa与bbb不同,跨域)
    http://www.111.com:8000/index.html 调用 http://www.111.com:5000/server.php
    (端口号不同:8000/5000,跨域)
    http://www.111.com/index.html 调用 https://www.111.com/server.php
    (协议不同:http/https,跨域)
    注:localhost和127.0.0.1都指向本机,但也属于跨域。

  2. 解决方案
    前端vue代码:

    main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Axios from 'axios'
Axios.defaults.baseURL = "http://localhost:8081"   
Vue.prototype.$axios = Axios
Vue.config.productionTip = false
new Vue({
  router,
  render: h => h(App),
  store
}).$mount('#app')

home.vue调用


  created() {
      this.$axios.get('/home')
        .then(function (res) {
          console.log(res);
        })
        .catch(function (err) {
          console.log(err);
        });
  }

后端node代码:

app.js

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const router = require('./router')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));

//跨域问题解决方案
const cors = require('cors');  
app.use(cors({  
    origin:['http://localhost:8080'],
    methods:['GET','POST'],
}));
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
 next(); 
})
//=================
app.use(express.static(path.resolve(__dirname, '../dist')));

app.use(router)

app.listen(8081, function () {
  console.log('success listen...8081');
});

router.js

const express = require('express')
const router = express.Router()

router.get('/home', function (req, res) {
    let data = {
        code:0,
        data:{name:'Franklin',pwd:8888},
        isSuccess:true,
        msg:'successful!'
    };
    res.json(data);
});

module.exports = router

=========================================================
成功解决!在这里插入图片描述

### 如何在 Vue 项目中使用 `node-red-contrib-vue` 组件 为了在 Vue 项目中集成并使用 `node-red-contrib-vue` 组件,需遵循特定步骤来设置环境和配置文件。此过程涉及安装必要的依赖项以及创建相应的节点定义。 #### 安装 Node-RED 和相关插件 Node-RED 是一个基于浏览器的编程工具,用于连接硬件设备、API 及在线服务。要开始,在本地环境中安装 Node-RED: ```bash npm install -g --unsafe-perm node-red ``` 接着,通过 npm 命令行工具安装 `node-red-contrib-vue` 插件[^1]: ```bash cd ~/.node-red npm install node-red-contrib-vue ``` #### 创建 Vue 应用程序并与 Node-RED 集成 对于现有的 Vue CLI 构建的应用程序,可以通过 WebSockets 或 HTTP 请求与运行中的 Node-RED 实例通信。一种方法是在 Vue 中引入 WebSocket 连接库,并将其链接到由 Node-RED 提供的服务端点上。 另一种更简便的方式是利用 `node-red-dashboard` 节点提供的 iframe 小部件功能直接嵌入仪表板页面至前端应用内显示。这允许开发者轻松地将交互式控件放置于任何 HTML 页面之中而不必担心资源共享(CORS)问题的发生。 如果希望进一步定制化,则可以考虑开发自定义 UI 控制器作为独立的小型 SPA (单页应用程序),再经由 RESTful API 同步数据给后台逻辑处理单元即 Node-RED 流程图编辑界面下的各个模块实例对象。 #### 编写 Node-RED 流程以支持 Vue 组件调用 启动 Node-RED 并打开其图形化设计平台后,拖拽所需的输入/输出节点到工作区中央空白处形成一条完整的消息传递路径。针对本案例而言,可选用 inject、function、http request/response 等基础构建块配合 vue-specific 的专用组件完成双向通讯机制的设计实现。 例如,下面是一个简单的流程片段展示如何接收来自客户端发起的一个 GET 类型请求并将响应结果返回给对方: ```json [ { "id": "e7b8a6f.dfa5c", "type": "http in", "z": "d34f9bdc.0cfbe8", "name": "", "url": "/api/data", "method": "get", "upload": false, "swaggerDoc": "", "x": 120, "y": 160, "wires": [ ["vue-component"] ] }, { "id": "vue-component", "type": "vue component", "z": "d34f9bdc.0cfbe8", "name": "MyComponent", "props": {}, "events": [], "methods": {}, "computed": {}, "watchers": {}, "template": "<div>Hello from MyComponent!</div>", "css": ".my-class { color: red; }" } ] ``` 上述 JSON 片段展示了如何配置 http-in 输入节点监听 `/api/data` 地址上的访问行为;紧接着触发名为 “MyComponent”的 Vue 自定义元素渲染输出一段静态文本内容。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值