nginx跨域

写的好渣啊,大家别看了,写的有点问题,哈哈

module.exports = function (app) { //设置跨域访问 app.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(); }); app.get('/getdata', function(req, res) { // res.send({id:req.params.id, name: req.params.password}); // res.send("hello"); res.json("hello"); }); }

const express = require('express')
const app = express()

const api = require('./api')
api(app)

app.listen(8889)
console.log("listen on port 8889");

  


$.ajax({ dataType: 'json', url: 'localhost:8889/server', type:'get', success: function(data){ console.log(data); } });

  node后台,前端nginx服务器ajax访问,出现跨域问题,使用nginx反向代理,一定得有http加上

location / {
root D:/myhtml;
index index.html;
}

location /projectname/ {
proxy_pass http://192.168.1.1:80;
proxy_redirect default;
}

这是一个匹配规则,上面的表示都匹配不到,就走上面的/这个

下面的表示,如果能匹配到xxxapi就优先走下面的,

比如我把静态资源放在myhtml中,接口在192.168.1.1:80/projectname/中。

访问接口的时候,就不需要些192.168.1.1:80这个东西啦哈哈

原文地址:https://www.cnblogs.com/beimingbingpo/p/8464207.html