I have react app running fine. I want to use phantom.js
for SEO. With the help of phantom.js, I want to store my page somewhere, and whenever a request comes from search bots, I want to serve them these saved pages.
The phantom.js code is:
var page;
var myurl="http://localhost:8080/login";
var renderPage = function (url) {
page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1';
page.onNavigationRequested = function(url, type, willNavigate, main) {
if (main && url!=myurl) {
myurl = url;
console.log("redirect caught");
page.close()
renderPage(url);
}
};
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
window.setTimeout(function () {
console.log(page.content);
phantom.exit();
}, 1000); // Change timeout as required to allow sufficient time
}
});
// page.open(url, function(status) {
// console.log(status);
// if (status==="success") {
// console.log("success")
// console.log(page.content);
// // page.render('yourscreenshot.png');
// phantom.exit(0);
// } else {
// console.log("failed")
// phantom.exit(1);
// }
// });
}
renderPage(myurl);
Above code works fine, but with two constraints:
It works only on localhost, i.e., if
myurl="http://localhost:8080/login";
is changed tomyurl="http://192.168.x.x/login";
, it doesn't work.If I am dynamically loading my component in react.js, above code doesn't work, even for localhost.
e.g., this works fine:
import Login from './containers/Login';
But, this doesn't:
const login = asyncComponent(() => import('./containers/login')
.then(module => module.default), { name: 'login' });
Where asyncComponent() is:
import React from 'react';
export default (loader, collection) => (
class AsyncComponent extends React.Component {
constructor(props) {
super(props);
this.Component = null;
this.state = { Component: AsyncComponent.Component };
}
componentWillMount() {
if (!this.state.Component) {
loader().then((Component) => {
AsyncComponent.Component = Component;
this.setState({ Component });
});
}
}
render() {
if (this.state.Component) {
return (
<this.state.Component { ...this.props } { ...collection } />
)
}
return null;
}
}
);
I am looking for some help/guidance for:
- How to manage SEO pages for reactjs? Is phantom.js a feasible solution?
- How to manage redirects, i.e., for request on servers, I first redirect request to index.html and then render the page. I want to do the same in phantom.js, get the page after redirection, which is not working fine.