我的AngularJS调用Glassdoor API时出现问题。它一直给我没有'Access-Control-Allow-Origin'标题出现在请求的资源上。
$http.get('https://api.glassdoor.com/api/api.htm?t.p=P_KEY&t.k=KEY&userip=0.0.0.0&useragent=&format=json&v=1&action=employers&q=ibm').then(function(resp) {
console.log(resp.data);
$scope.employers = resp.data;
}, function(error, resp) {
console.log(error, resp);
});
如果我专门点击链接但角度调用没有,它确实有效。
Server.js处理CORS。
var express = require('express');
var mysql = require('mysql');
//var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var app = express();
var cors = require('cors');
var serveStatic = require('serve-static');
var data = '';
var connection = mysql.createConnection({
host: 'localhost',
port: '3306',
user: 'root',
password: '',
database: 'jobs'
});
//app.use(cors({origin: 'http://localhost:YOUR_PORT'}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(serveStatic(require("path").join(__dirname, "/views"))); // Serves everything in the views directory
// Example: url.com/css/style.css serves views/css/style.css
app.get('/api/jobs', function(req, res, next) {
connection.query('SELECT * FROM jobs ORDER BY company ASC', function(err, results) {
if (err) {
console.log('There was a problem reading from jobs database :' + err.stack);
res.sendStatus(500).send('There was a problem reading from jobs database');
return;
}
console.log('results:', results);
res.send(results);
});
});
app.post('/api/jobs_post', function(req, res, next){
});
var server = app.listen(8081, function() {console.log("Running")});
var gracefulShutdown = function() {
console.log('Shutting down');
server.close(function() {
console.log('Closed out remaining connections');
});
connection.end(function(err) {
if (err) {
console.log('There was an error closing the connection to jobs database: ' + err.stack);
} else {
console.log('Connection terminated successfully!')
}
});
}
process.on('SIGTERM', gracefulShutdown); // Server is killed
process.on('SIGINT', gracefulShutdown); // Ctrl-C is pressed in the terminal
这是我有趣的个人项目:https://csjobsco-gchavez1011.c9users.io:8081/index.html
答案 0 :(得分:0)
您直接从浏览器调用Glassdoor API,因此出现“不允许”的交叉来源错误 你必须从服务器或通过代理进行调用(我猜这就是server.js的用途)。