03 为基于Express框架创建的Node后台配置跨域访问

写在前面

跨域这个问题只要是涉及前后端数据交互,就会经常遇到,所以我们开发中也一样,即便你是在本地启动后台服务,然后在你的项目中去调用,依然存在跨域问题,所以我们要为我们新建的NodeJS后台配置跨域访问,也就是说让它允许跨域访问。

环境要求

  • 安装了NodeJS环境(可以使用npm包管理工具)
  • 初始化了一个NodeJS后台项目demo

操作步骤

1、在index.js文件中添加如下代码即可:

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-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();
});

2、最终的index.js文件代码如下所示:

var express = require('express');
var app = express();

var home = require('./routers/home');
var geocode = require('./routers/geocode');

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-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();
});

app.use('/', home);
app.use('/geocode', geocode);

app.listen(3001);

总结

NodeJS的后台配置跨域其实很简单,只需要添加文中的几行代码即可实现后台接口的跨域访问。

猜你喜欢

转载自blog.csdn.net/qq_35117024/article/details/107465678
03
今日推荐