express解決跨域

最近開(kāi)始搭建個(gè)人博客, 遇到的第一個(gè)問(wèn)題是跨域問(wèn)題, 因?yàn)樽詈蠛喜⒌揭粋€(gè)項(xiàng)目里需要臨時(shí)跨域. 需要解決下臨時(shí)跨域的問(wèn)題.

Vue.axios.get('http://192.168.4.14:3000/index').then((response) => {
  console.log(response.data)
}

解決跨域問(wèn)題的方法有很多, 此次添加中間件設(shè)置header的方式解決跨域

//設(shè)置跨域訪問(wèn)
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

添加一個(gè)中間件在所有需要跨域的路由之前即可


例:
后臺(tái)設(shè)置index路由

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

//設(shè)置跨域訪問(wèn)
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

/* GET home page. */
router.get('/index', function(req, res, next) {
  // res.render('index', { title: 'Express' });
    res.send('跨域請(qǐng)求')
});

module.exports = router;

前端使用 axios請(qǐng)求

const cityGuess = () => Vue.axios.get('http://localhost:3000/index').then((response) => {
  console.log(response.data)
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • (全局解決)核心代碼://設(shè)置跨域訪問(wèn)app.all('*', function(req, res, next) ...
    Husbin閱讀 2,180評(píng)論 0 0
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,694評(píng)論 19 139
  • Address:https://www.zybuluo.com/XiangZhou/note/208532 Exp...
    天蠍蒗漫閱讀 11,636評(píng)論 2 55
  • 1. 簡(jiǎn)介 這篇文章主要的目的是分析理解express的源碼,網(wǎng)絡(luò)上關(guān)于源碼的分析已經(jīng)數(shù)不勝數(shù),這篇文章準(zhǔn)備另辟蹊...
    沒(méi)事造輪子閱讀 1,493評(píng)論 0 8
  • 心靈自由第八期第15篇作業(yè) 昨天去一家理發(fā)店,想想也許可以改個(gè)發(fā)型。設(shè)計(jì)師給了我一些建議,比如臉型哪里寬了線條不夠...
    何偀閱讀 383評(píng)論 0 0

友情鏈接更多精彩內(nèi)容