React+Nodejs+Mongodb存储
React+Nodejs+mongodb存储
安装React
在此之前,请自行安装好Node和Mongodb数据库的配置
使用命令行创建文件:
npm install -g create-react-app
然后我们找到想要创建React的文件夹
- 在需要创建项目的位置打开命令行
- 输入create-react-app + 项目名称的命令,比如:
create-react-app Hello-World
等待完成创建后 通过CD命令进入,然后npm strat 就可以看到默认的文件了
cd Hello-World
npm start
创建后的默认目录
然后我们打开src创建一个js文件,加入我们的跨域请求端口
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://goo.gl/SC7cgQ'
);
});
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
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 => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
index.js中的代码块:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();//跨域js
然后在src里面创建一个组件之后导入到index.js里面来使用 我在这里创建了一个list.jsx的组件,下面是组件的代码:
import React from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import './list.css';
import axios from 'axios';
var url = 'http://localhost:3000/' //配置远程图片的默认地址
axios.defaults.baseURL = 'http://localhost:3000/'; //axios默认请求的域名或ip地址
class TrData extends React.Component{
constructor(props){
super(props);
this.state = {}
}
render(){
return (
this.props.products.map((product,i)=>{ //使用map循环遍历渲染数据库中的数据
return (
<tr key={product._id} className="text-center">
<td>{product.title}</td>
<td>
<img src={url+product.defaultImage} width="100" alt=""/>
</td>
<td>{product.category.title}</td>
<td>{product.price}</td>
<td>
<button type="button" className="btn btn-default">修改</button>
<button type="button" className="btn btn-danger">删除</button>
</td>
</tr>
)
})
)
}
}
class List extends React.Component {
constructor(props){
super(props);
this.state={
products:[], // 默认为空
isLoaded:false,
}
}
componentDidMount(){
const _this=this;
axios.get('/v1/shop/commodity/getlist')
.then(function (response) {
_this.setState({
products:response.data.data.list, //请求到的数据
isLoaded:true
});
})
.catch(function (error) {
console.log(error);
_this.setState({
isLoaded:false,
error:error
})
})
}
render() {
//条件渲染 与Vue的 V-if相似
if(!this.state.isLoaded){
return <div>Loading</div>
}else{
return (
<table className="table table-striped">
<thead>
<tr>
<th className="text-center">商品名称</th>
<th className="text-center">商品图片</th>
<th className="text-center">商品分类</th>
<th className="text-center">商品价格</th>
<th className="text-center">操作</th>
</tr>
</thead>
<tbody>
<TrData products={this.state.products}/>
</tbody>
</table>
)
}
}
}
export default List;//导出List组件
App.js中把list.jsx组件导入进来
import List from './List.jsx'; //导入list组件
class App extends Component {
constructor(props){
super(props); // 继承父类属性
this.state={ }
}
//渲染list
render() {
return (
<div className="container"> //这里也可以写样式,我这里写的是Bootstrap的一个样式
<List /> //组件
</div>
);
}
}
然后把后台的地址以及Mongo数据库开启,对了这里忘了说了,因为NodeJS和ReactJS的默认端口都是localhost:3000 我们可以先把React的启动端口修改一下 在package.json的Start项里面修改为
“start”: “set PORT = 端口号 && react-scripts start” 例如:
"start": "set PORT = 9000 && react-scripts start"
然后我们 npm start 你就会发现默认改成了localhost:9000 这样,数据就渲染到了页面上
至此,我们的数据渲染就大功告成了