Node.js + Express +跨域脚本

时间:2022-04-06 04:50:57

I am testing on localhost, and using module CORS strange ... POST ajax call to get access_token ( using module node-oauth2-server ) succeed but then trying to access resources, ajax calls are failing ( Origin ...not allowed by Access-Control-Allow-Origin) I guess there is something wrong in my routing ...

我在localhost上测试,并使用模块CORS奇怪... POST ajax调用get access_token(使用模块node-oauth2-server)成功但是然后尝试访问资源,ajax调用失败(Origin ...不允许访问-Control-Allow-Origin)我猜我的路由有问题...

var express = require('express'),
cors = require('cors'),
http = require('http'),
https = require('https'),
fs = require('fs'),
oauthserver = require('node-oauth2-server'),
categories = require('./models/category'),
products = require('./models/product');

var server_options = {
key: fs.readFileSync('/etc/ssl/self-signed/server.key'),
cert: fs.readFileSync('/etc/ssl/self-signed/server.crt')
};

var app = express();

//app.use(require('cors')());
app.use(require('browser-logger')());

app.use(cors()); // automatically supports pre-flighting
app.use(app.router);

app.configure(function() {
  var oauth = oauthserver({
    model: require('./models/oauth_mongodb'),
     // See below for specification
    grants: ['password', 'refresh_token'],
    accessTokenLifetime: 2592000,  // 30 days
    debug: true
});
app.use(express.bodyParser()); // REQUIRED
app.use(oauth.handler());
app.use(oauth.errorHandler());
});

// categories
app.get('/categories/:id', categories.findById);
app.get('/categories', categories.findAll);

// products
app.get('/categories/:id/products', products.findByCategory);
app.get('/products/:id', products.findById);
app.get('/products', products.findAll);

https.createServer(server_options,app).listen(8000, 'node_ssl_server.local');
http.createServer(app).listen(3000, 'node_ssl_server.local');

1 个解决方案

#1


1  

Just a guess, but I think your ajax calls are probably originating from:

只是一个猜测,但我认为你的ajax调用可能来自:

http://localhost:3000/ 

and pointing at

并指着

https://localhost:8000/

You may need to do a browser refresh to avoid the cross domain error.

您可能需要进行浏览器刷新以避免跨域错误。

#1


1  

Just a guess, but I think your ajax calls are probably originating from:

只是一个猜测,但我认为你的ajax调用可能来自:

http://localhost:3000/ 

and pointing at

并指着

https://localhost:8000/

You may need to do a browser refresh to avoid the cross domain error.

您可能需要进行浏览器刷新以避免跨域错误。