我是Angular的新手,我正在尝试构建一个简单的应用程序来自学。我不明白为什么我会收到主题中提到的错误? " XMLHttpRequest无法加载localhost:8081 / scrape。交叉源请求仅支持协议方案:http,数据,chrome,chrome-extension,https,chrome-extension-resource。"
我导航到我指定的端口(8081),但即使我通过express启用了cors,我也收到了CORS错误:
Angular Factory:
.factory('TradesDataFactory', function($http) {
var getPlayerInfo = function() {
return $http({
method: 'GET',
url: 'localhost:8081/scrape'
}).then(function(resp) {
return resp.data
});
};
表达:刮痧
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var cors = require('express-cors')
var app = express();
app.use(cors());
app.use(express.static('client'));
//*** how do I get this to scrape on server load?
app.get('/scrape', function(req, res) {
//All the web scraping magic will happen here. do this once.
url = "https://www.bing.com/search?q=Week+1+running%20backs+fantasy+predictions&FORM=MA12R5&OCID=MA12R5&wt.mc_id=MA12R5";
request(url, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html);
var player, projectedPoints;
var players = [];
var playersAndPoints = $('.items').text();
var playersAndPoints = JSON.stringify(playersAndPoints);
var re = /Points\s\(PPR\)/gi;
var formattedPlayers = playersAndPoints.replace(re, " ");
formattedPlayers.replace("\\\"", "\"");
var regex2 = /\.\d/g;
var formattedPlayers = formattedPlayers.split(regex2);
console.log(formattedPlayers);
var names = formattedPlayers.map(function(player) {
return player.split(':')[0]
});
var score = formattedPlayers.map(function(player) {
return player.split(':')[1]
});
var object = {}
for (var i = 0; i < names.length; i++) {
object[names[i]] = score[i];
}
}
var formattedPlayers = object;
fs.writeFile('output.json', JSON.stringify(formattedPlayers, null, 4), function(err) {
console.log("check your file directory!")
})
res.send("check your console!")
})
})
app.listen('8081')
console.log('Magic happens on port 8081');
exports.app = app;
答案 0 :(得分:0)
您收到的错误是Angular检查网址的协议,例如div
,http
或data
。
如果您将url参数更改为:file
,它应该可以正常工作,使您的$ http方法看起来像:
url: 'http://localhost:8081/scrape'