socket长连接运行在http协议上时,浏览器报出错误。在使用Apache反向代理,React的serviceWorker会报出错误,如下所示:
Error during service worker registration: DOMException: Only secure origins are allowed (see: [https://goo.gl/Y0ZkNV](https://goo.gl/Y0ZkNV)).
之前一直是浏览器报出的,我用静态页面测试下,没报出这个错误,尴尬了,是react报出的。
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
websocket的错误是由registerServiceWorker();引起,打开registerServiceWorker文件,可以看到这段代码:
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
//here
console.error('Error during service worker registration:', error);
});
}
在index.js文件中,注释掉这段代码,如下所示:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// registerServiceWorker();
运行项目时,将没有报错,如下所示:
参考网站:
- 错误解决过程: https://translate.google.com/translate?hl=en&sl=en&tl=zh-CN&u=https%3A%2F%2Fgithub.com%2Ffacebook%2Fcreate-react-app%2Fissues%2F2413
- chrome安全策略: https://translate.googleusercontent.com/translate_c?depth=1&hl=en&rurl=translate.google.com&sl=en&sp=nmt4&tl=zh-CN&u=https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features&xid=17259,15700023,15700124,15700149,15700168,15700186,15700190,15700201,15700208&usg=ALkJrhh93ijJd47ftZNjhWw0RhlGn34pvg
- create-react-app源码地址: https://github.com/facebook/create-react-app/blob/e898215b7ffcc436306e209227fcf393d134fe69/packages/react-scripts/template/src/index.js#L8