美文网首页
express解决跨域

express解决跨域

作者: Nick_BW_Zhao | 来源:发表于2017-04-24 14:59 被阅读0次

最近开始搭建个人博客, 遇到的第一个问题是跨域问题, 因为最后合并到一个项目里需要临时跨域. 需要解决下临时跨域的问题.

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

解决跨域问题的方法有很多, 此次添加中间件设置header的方式解决跨域

//设置跨域访问
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();
});

添加一个中间件在所有需要跨域的路由之前即可


例:
后台设置index路由

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

//设置跨域访问
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('跨域请求')
});

module.exports = router;

前端使用 axios请求

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

相关文章

网友评论

      本文标题:express解决跨域

      本文链接:https://www.haomeiwen.com/subject/bxlpzttx.html