本文共 2153 字,大约阅读时间需要 7 分钟。
前后端交互时,跨域问题是必须要解决的重要课题。以下是解决跨域问题的几种常用方法及实践案例。
在前后端分离开发中,CORS是一种常用的解决跨域问题的方法。通过设置CORS策略,可以允许从指定或所有域请求接口。
app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By", 'unknown'); res.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); next();}); Access-Control-Allow-Origin: * 表示允许所有域名请求接口。http://www.wtapi.wang。当需要对后端接口进行转发时,可以使用Node.js Express框架进行路由转发。以下是一个典型的实现示例:
const request = require('request');app.get('/api/apiturntest', function(req, res) { request('http://127.0.0.1:8008/api/essayNote', function(error, response, body) { if (error) { console.error('请求失败:', error); } else { res.send(body); } });}); npm install request
如果需要将多个接口代理到本地开发环境,可以使用代理工具或自行开发一个代理服务。
axios等工具在前端直接代理接口。const express = require('express');const router = express.Router();const request = require('request');router.get('/api/apiturntest', function(req, res) { request('http://127.0.0.1:8008/api/essayNote', function(error, response, body) { if (error) { console.error('请求失败:', error); } else { res.send(body); } });});app.use('/api', router);app.listen(8009, function() { console.log('服务器已启动在8009端口');}); 在前端使用axios或XMLHttpRequest发起请求时,需确保后端接口支持CORS。
this.$http.get('http://127.0.0.1:8008/api/essayNote') .then(response => { console.log(response.data); }) .catch(error => { console.error('请求失败:', error); }); CORS中间件或反向代理。通过以上方法,可以有效解决前后端跨域问题,实现接口的正常调用。
转载地址:http://ltikz.baihongyu.com/