I know there are so many explanations out there, but it still doesn't solve my current problem.
Basically, I was using /sth
and ``/sthElseto render into my index.html (which is
/`) because one is post another one is comments, I did include the header in my server, but but I still got an error says:
XMLHttpRequest cannot load file:///sth. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
//client jquery ajax
function something(){
$.ajax({
method: 'GET',
url: '/sth',
headers: headers,
success: function(data) {
console.log(data);
}
});
}
function somethingElse(){
$.ajax({
method: 'GET',
url: '/sthElse',
success: function(data) {
console.log('comment',data);
}
}
}
});
}
// server express
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get('/sth', function(request, response){
var req = http.get(url+"posts", function(res){
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
})
.on('end', function() {
var body = Buffer.concat(bodyChunks);
response.send(JSON.parse(body));
})
});
req.on('error', function(e) {
console.log('ERROR');
});
});
app.get('/sthElse', function(request, response){
console.log('STATUSasdf: ' + response.statusCode);
var req = http.get(url+'comments', function(res) {
var bodyChunks = [];
res.on('data', function (chunk) {
bodyChunks.push(chunk);
})
.on('end', function() {
console.log('this is bodychunks pre decription', bodyChunks);
var body = Buffer.concat(bodyChunks);
response.send(JSON.parse(body));
})
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
});