var express = require('express');
var app = express();
app.get('/heart', function (req, res) {
res.json({message: 'Love from the server!'});
});
app.listen(3000, function () {
console.log('Express app listening at http://localhost:3000');
});
使用 express cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors()); // 使用 CORS 中间件,表明允许所有源的请求
app.get('/heart', function (req, res) {
res.json({message: 'Love from the server!'});
});
app.listen(3000, function () {
console.log('Express app listening at http://localhost:3000');
});
无 cors + nginx 配置实现跨域
nginx 配置如下,下面的配置还不完整,无法实现 CORS。
server {
listen 80;
server_name localhost;
location /api/ {
proxy_pass http://192.168.1.104:3000/; # 末尾添加斜线
# location 删除前缀 /api
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
# split /api/ to / and heart in $1, then append /$1 after proxy_pass
rewrite ^/api/(.*) /$1 break;
}
}