我设置了一个服务器http://本地主机:8080 http://localhost:8080 where http://example.com http://example.com可以执行 POST 请求:
'use strict';
const express = require('express');
const app = express();
const port = 8080;
// allowing CORS for example.com
app.use('/', function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://example.com');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'OPTIONS, POST');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length');
res.status(200).send();
} else {
next();
}
});
// handling POST requests
app.use('/', function (req, res) {
console.log('a client did a POST request');
res.status(200);
});
app.listen(port, () => console.log ('server started on port ' + port));
它工作正常:我无法执行 POST 请求http://本地主机:8080 http://localhost:8080 from http://本地主机:8081 http://localhost:8081因为同源政策。
然后我为 Firefox 编写了一个 Web 扩展,它将尝试向http://本地主机:8080 http://localhost:8080来自任何域。
这是它的清单:
{
"manifest_version" : 2,
"name" : "aBasicExtension",
"version" : "0.0.0",
"content_scripts" : [
{
"matches" : ["<all_urls>"],
"js" : ["content-script.js"]
}
],
"permissions" : ["*://*.localhost/*"]
}
and its content-script.js
code :
(() => {
'use strict';
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080');
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === XMLHttpRequest.DONE){
if (xhr.status === 200) console.log('OK');
else console.error('an error has occured : ' + xhr.status);
}
});
xhr.send(JSON.stringify({dataName: 'some data here'}));
})();
我不明白的是它有效。扩展程序执行请求http://本地主机:8080 http://localhost:8080Firefox 并没有阻止它,因为清单允许它,但是服务器(http://本地主机:8080 http://locahost:8080) 没有得到他的许可.