asp網(wǎng)站亂碼百度推廣在線客服
目錄:
- 腳手架配置代理_方法一
- server1.js
- 開啟服務器server1:
- App.js
- 解決跨域問題:
- 腳手架配置代理_方法二
- ???????server2.js
- 開啟服務器server2
- 第一步:創(chuàng)建代理配置文件
- 編寫setupProxy.js配置具體代理規(guī)則:
- App.js
- 運行結(jié)果:
- 說明:
- github用戶搜索案例
- github搜索案例_靜態(tài)組件
- github搜索案例_axios發(fā)送請求
- github搜索案例_展示數(shù)據(jù)
- github搜索案例_完成案例
- 消息訂閱與發(fā)布_pubsub
- fetch發(fā)送請求
1.腳手架配置代理_方法一
server1.js
const express = require('express')
const app = express()app.use((request,response,next)=>{console.log('有人請求服務器1了');console.log('請求來自于',request.get('Host'));console.log('請求的地址',request.url);next()
})app.get('/students',(request,response)=>{const students = [{id:'001',name:'tom',age:18},{id:'002',name:'jerry',age:19},{id:'003',name:'tony',age:120},]response.send(students)
})app.listen(5000,(err)=>{if(!err) console.log('服務器1啟動成功了,請求學生信息地址為:http://localhost:5000/students');
})
開啟服務器server1:
App.js
import React, {Component} from 'react';
import axios from "axios";class App extends Component {getStudentData = () => {axios.get('http://localhost:5000/students').then(response => {console.log('成功了', response.data);},error => {console.log('失敗了', error);})}render() {return (<div><button onClick={this.getStudentData}>點我獲取學生數(shù)據(jù)</button></div>);}
}export default App;
解決跨域問題:
package.json
{"name": "20231003","version": "0.1.0","private": true,"dependencies": {"@testing-library/jest-dom": "^5.17.0","@testing-library/react": "^13.4.0","@testing-library/user-event": "^13.5.0","axios": "^1.5.1","nanoid": "^5.0.1","prop-types": "^15.8.1","react": "^18.2.0","react-dom": "^18.2.0","react-scripts": "5.0.1","web-vitals": "^2.1.4"},"scripts": {"start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"},"eslintConfig": {"extends": ["react-app","react-app/jest"]},"browserslist": {"production": [">0.2%","not dead","not op_mini all"],"development": ["last 1 chrome version","last 1 firefox version","last 1 safari version"],"proxy": "http://localhost:5000"}
}
使用方法一遇到了bug,去stackoverflow解決一下,能解決,但是有更好的方法,方法一不在繼續(xù)了.node.js - Invalid options object. Dev Server has been initialized using an options object that does not match the API schema - Stack Overflow
2.腳手架配置代理_方法二
server2.js
const express = require('express')
const app = express()app.use((request,response,next)=>{console.log('有人請求服務器2了');next()
})app.get('/cars',(request,response)=>{const cars = [{id:'001',name:'奔馳',price:199},{id:'002',name:'馬自達',price:109},{id:'003',name:'捷達',price:120},]response.send(cars)
})app.listen(5001,(err)=>{if(!err) console.log('服務器2啟動成功了,請求汽車信息地址為:http://localhost:5001/cars');
})
開啟服務器server2
訪問端口:
第一步:創(chuàng)建代理配置文件
在src下創(chuàng)建配置文件:src/setupProxy.js
編寫setupProxy.js配置具體代理規(guī)則:
這個適合低版本
const proxy = require('http-proxy-middleware')
module.exports = function(app) {
? app.use(
? ? proxy('/api1', { ?//api1是需要轉(zhuǎn)發(fā)的請求(所有帶有/api1前綴的請求都會轉(zhuǎn)發(fā)給5000)
? ? ? target: 'http://localhost:5000', //配置轉(zhuǎn)發(fā)目標地址(能返回數(shù)據(jù)的服務器地址)
? ? ? changeOrigin: true, //控制服務器接收到的請求頭中host字段的值
? ? ? /*
? ? ? ?? ?changeOrigin設置為true時,服務器收到的請求頭中的host為:localhost:5000
? ? ? ?? ?changeOrigin設置為false時,服務器收到的請求頭中的host為:localhost:3000
? ? ? ?? ?changeOrigin默認值為false,但我們一般將changeOrigin值設為true
? ? ? */
? ? ? pathRewrite: {'^/api1': ''} //去除請求前綴,保證交給后臺服務器的是正常請求地址(必須配置)
? ? }),
? ? proxy('/api2', {?
? ? ? target: 'http://localhost:5001',
? ? ? changeOrigin: true,
? ? ? pathRewrite: {'^/api2': ''}
? ? })
? )
}
我使用的node是:v18.18.0?
//react 18版本寫法 const {createProxyMiddleware} = require('http-proxy-middleware')module.exports = function (app) {app.use(createProxyMiddleware('/api1', {target: 'http://localhost:5000',changeOrigin: true,pathRewrite: {'^/api1': ''}}),createProxyMiddleware('/api2', {target: 'http://localhost:5001',changeOrigin: true,pathRewrite: {'^/api2': ''}}),) }
App.js?
import React, {Component} from 'react';
import axios from "axios";class App extends Component {getStudentData = () => {axios.get('http://localhost:3000/api1/students').then(response => {console.log('成功了', response.data);},error => {console.log('失敗了', error);})}getCarData = () => {axios.get('http://localhost:3000/api2/cars').then(response => {console.log('成功了', response.data);},error => {console.log('失敗了', error);})}render() {return (<div><button onClick={this.getStudentData}>點我獲取學生數(shù)據(jù)</button><button onClick={this.getCarData}>點我獲取汽車數(shù)據(jù)</button></div>);}
}export default App;
運行結(jié)果:
說明:
-
優(yōu)點:可以配置多個代理,可以靈活的控制請求是否走代理。
-
缺點:配置繁瑣,前端請求資源時必須加前綴。
3.github用戶搜索案例
github搜索案例_靜態(tài)組件
App.js
import React, {Component} from 'react';
import Search from './components/Search/Search'
import List from "./components/List/List";class App extends Component {render() {return (<div><div className="container"><Search></Search><List></List></div></div>);}
}export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
?List.jsx
import React, {Component} from 'react';
import './List.css'class List extends Component {render() {return (<div><div className="row"><div className="card"><a rel="noreferrer" href="https://github.com/reactjs" target="_blank"><img alt="head_protrait" src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/></a><p className="card-text">reactjs</p></div></div></div>);}
}export default List;
?List.css
.album {min-height: 50rem; /* Can be removed; just added for demo purposes */padding-top: 3rem;padding-bottom: 3rem;background-color: #f7f7f7;
}.card {float: left;width: 33.333%;padding: .75rem;margin-bottom: 2rem;border: 1px solid #efefef;text-align: center;
}.card > img {margin-bottom: .75rem;border-radius: 100px;
}.card-text {font-size: 85%;
}
Search.jsx
import React, {Component} from 'react';class Search extends Component {render() {return (<div><section className="jumbotron"><h3 className="jumbotron-heading">Search Github Users</h3><div><input type="text" placeholder="enter the name you search"/> <button>Search</button></div></section></div>);}
}export default Search;
運行結(jié)果:
?
github搜索案例_axios發(fā)送請求
demo.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<script type="text/javascript">let obj = {a: {b: {c: 1}}}let obj2 = {a: {b: 1}}console.log(obj.a.b.c)const {a: {b: {c}}} = objconsole.log(c)const {a: {b: data}} = obj2console.log(data)
</script>
</body>
</html>
server.js
const express = require("express")
const axios = require("axios")
const app = express()/*請求地址: http://localhost:3000/search/users?q=aa后臺路由key: /search/usersvalue: function () {}
*/
app.get("/search/users", function (req, res) {const {q} = req.queryaxios({url: 'https://api.github.com/search/users',params: {q}}).then(response => {res.json(response.data)})
})app.get("/search/users2", function (req, res) {res.json({items: [{login: "yyx990803",html_url: "https://github.com/yyx990803",avatar_url:"https://avatars3.githubusercontent.com/u/499550?s=460&u=de41ec9325e8a92e281b96a1514a0fd1cd81ad4a&v=4",id: 1,},{login: "ruanyf",html_url: "https://github.com/ruanyf",avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4",id: 2,},{login: "yyx9908032",html_url: "https://github.com/yyx990803",avatar_url:"https://avatars3.githubusercontent.com/u/499550?s=460&u=de41ec9325e8a92e281b96a1514a0fd1cd81ad4a&v=4",id: 3,},{login: "ruanyf2",html_url: "https://github.com/ruanyf",avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4",id: 4,},{login: "yyx9908033",html_url: "https://github.com/yyx990803",avatar_url:"https://avatars3.githubusercontent.com/u/499550?s=460&u=de41ec9325e8a92e281b96a1514a0fd1cd81ad4a&v=4",id: 5,},{login: "ruanyf3",html_url: "https://github.com/ruanyf",avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4",id: 6,},{login: "yyx9908034",html_url: "https://github.com/yyx990803",avatar_url:"https://avatars3.githubusercontent.com/u/499550?s=460&u=de41ec9325e8a92e281b96a1514a0fd1cd81ad4a&v=4",id: 7,},{login: "ruanyf4",html_url: "https://github.com/ruanyf",avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4",id: 8,},{login: "yyx9908035",html_url: "https://github.com/yyx990803",avatar_url:"https://avatars3.githubusercontent.com/u/499550?s=460&u=de41ec9325e8a92e281b96a1514a0fd1cd81ad4a&v=4",id: 9,},],});
});app.listen(5000, "localhost", (err) => {if (!err){console.log("服務器啟動成功")console.log("請求github真實數(shù)據(jù)請訪問:http://localhost:5000/search/users")console.log("請求本地模擬數(shù)據(jù)請訪問:http://localhost:5000/search/users2")} else console.log(err);
})
啟動服務器:
node .\server.js
?App.js
import React, {Component} from 'react';
import Search from './components/Search/Search'
import List from "./components/List/List";class App extends Component {render() {return (<div><div className="container"><Search></Search><List></List></div></div>);}
}export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
List.jsx
import React, {Component} from 'react';
import './List.css'class List extends Component {render() {return (<div><div className="row"><div className="card"><a rel="noreferrer" href="https://github.com/reactjs" target="_blank"><img alt="head_protrait" src="https://avatars.githubusercontent.com/u/6412038?v=3" style={{width:'100px'}}/></a><p className="card-text">reactjs</p></div></div></div>);}
}export default List;
List.css
.album {min-height: 50rem; /* Can be removed; just added for demo purposes */padding-top: 3rem;padding-bottom: 3rem;background-color: #f7f7f7;
}.card {float: left;width: 33.333%;padding: .75rem;margin-bottom: 2rem;border: 1px solid #efefef;text-align: center;
}.card > img {margin-bottom: .75rem;border-radius: 100px;
}.card-text {font-size: 85%;
}
Search.jsx
import React, {Component} from 'react';
import axios from "axios";class Search extends Component {search = () => {//連續(xù)結(jié)構+重命名const {keyWordElement: {value: keyWord}} = thisaxios.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`).then(response => {console.log('成功了', response.data);},error => {console.log('失敗了', error);})}render() {return (<div><section className="jumbotron"><h3 className="jumbotron-heading">搜索github用戶</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/> <button onClick={this.search}>搜索</button></div></section></div>);}
}export default Search;
?setupProxy.js
//react 18版本寫法
const {createProxyMiddleware} = require('http-proxy-middleware')module.exports = function (app) {app.use(createProxyMiddleware('/api1', {target: 'http://localhost:5000',changeOrigin: true,pathRewrite: {'^/api1': ''}}),)
}
?
運行結(jié)果:
?
github搜索案例_展示數(shù)據(jù)
App.js
import React, {Component} from 'react';
import Search from './components/Search/Search'
import List from "./components/List/List";class App extends Component {state = {users: []}saveUsers = (users) => {this.setState({users})}render() {const {users} = this.statereturn (<div><div className="container"><Search saveUsers={this.saveUsers}></Search><List users={users}></List></div></div>);}
}export default App;
List.jsx
import React, {Component} from 'react';
import './List.css'class List extends Component {render() {return (<div><div className="row">{this.props.users.map((userObj) => {return (<div className="card" key={userObj.id}><a rel="noreferrer" href={userObj.html_url} target="_blank"><img alt="head_protrait"src={userObj.avatar_url}style={{width: '100px'}}/></a><p className="card-text">{userObj.login}</p></div>)})}</div></div>);}
}export default List;
?Search.jsx
import React, {Component} from 'react';
import axios from "axios";class Search extends Component {search = () => {//連續(xù)結(jié)構+重命名const {keyWordElement: {value: keyWord}} = thisaxios.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`).then(response => {console.log('成功了', response.data.items);this.props.saveUsers(response.data.items)},error => {console.log('失敗了', error);})}render() {return (<div><section className="jumbotron"><h3 className="jumbotron-heading">搜索github用戶</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/> <button onClick={this.search}>搜索</button></div></section></div>);}
}export default Search;
運行結(jié)果:
github搜索案例_完成案例
App.js
import React, {Component} from 'react';
import Search from './components/Search/Search'
import List from "./components/List/List";class App extends Component {state = {users: [], isFirst: true, isLoading: false, err: ''}saveUsers = (users) => {this.setState({users})}updateAppState = (stateObj) => {this.setState(stateObj)}render() {const {users} = this.statereturn (<div><div className="container"><Search updateAppState={this.updateAppState}></Search><List {...this.state}></List></div></div>);}
}export default App;
Search.jsx
import React, {Component} from 'react';
import axios from "axios";class Search extends Component {search = () => {//連續(xù)結(jié)構+重命名const {keyWordElement: {value: keyWord}} = thisconsole.log(keyWord)this.props.updateAppState({isFirst: false, isLoading: true})axios.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`).then(response => {console.log('成功了', response.data.items);this.props.updateAppState({isLoading: false, users: response.data.items})},error => {console.log('失敗了', error);this.props.updateAppState({isLoading: false, err: error.message})})}render() {return (<div><section className="jumbotron"><h3 className="jumbotron-heading">搜索github用戶</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/> <button onClick={this.search}>搜索</button></div></section></div>);}
}export default Search;
List.jsx
import React, {Component} from 'react';
import './List.css'class List extends Component {render() {const {users, isFirst, isLoading, err} = this.propsreturn (<div><div className="row">{isFirst ? <h2>歡迎使用,輸入關鍵字,然后點擊搜索</h2> :isLoading ? <h2>加載中...</h2> :err ? <h2 style={{color: 'red'}}>{err}</h2> :users.map((userObj) => {return (<div className="card" key={userObj.id}><a rel="noreferrer" href={userObj.html_url} target="_blank"><img alt="head_protrait"src={userObj.avatar_url}style={{width: '100px'}}/></a><p className="card-text">{userObj.login}</p></div>)})}</div></div>);}
}export default List;
?setProxy.js
//react 18版本寫法
const {createProxyMiddleware} = require('http-proxy-middleware')module.exports = function (app) {app.use(createProxyMiddleware('/api1', {target: 'http://localhost:5000',changeOrigin: true,pathRewrite: {'^/api1': ''}}),)
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
運行結(jié)果:
4.消息訂閱與發(fā)布_pubsub
App.js
import React, {Component} from 'react';
import Search from './components/Search/Search'
import List from "./components/List/List";class App extends Component {render() {return (<div><div className="container"><Search></Search><List></List></div></div>);}
}export default App;
List.jsx
import React, {Component} from 'react';
import './List.css'
import PubSub from 'pubsub-js'class List extends Component {state = {users: [], isFirst: true, isLoading: false, err: ''}componentDidMount() {this.token = PubSub.subscribe('atguigu', (_, stateObj) => {console.log(stateObj);this.setState(stateObj);})}componentWillUnmount() {PubSub.unsubscribe(this.token)}render() {const {users, isFirst, isLoading, err} = this.statereturn (<div><div className="row">{isFirst ? <h2>歡迎使用,輸入關鍵字,然后點擊搜索</h2> :isLoading ? <h2>加載中...</h2> :err ? <h2 style={{color: 'red'}}>{err}</h2> :users.map((userObj) => {return (<div className="card" key={userObj.id}><a rel="noreferrer" href={userObj.html_url} target="_blank"><img alt="head_protrait"src={userObj.avatar_url}style={{width: '100px'}}/></a><p className="card-text">{userObj.login}</p></div>)})}</div></div>);}
}export default List;
?Search.jsx
import React, {Component} from 'react';
import axios from "axios";
import PubSub from "pubsub-js";class Search extends Component {search = () => {//連續(xù)結(jié)構+重命名const {keyWordElement: {value: keyWord}} = thisconsole.log(keyWord)// this.props.updateAppState({isFirst: false, isLoading: true})PubSub.publish('atguigu', {isFirst: false, isLoading: true})axios.get(`http://localhost:3000/api1/search/users2?q=${keyWord}`).then(response => {console.log('成功了', response.data.items);// this.props.updateAppState({isLoading: false, users: response.data.items})PubSub.publish('atguigu', {isLoading: false, users: response.data.items})},error => {console.log('失敗了', error);// this.props.updateAppState({isLoading: false, err: error.message})PubSub.publish('atguigu', {isLoading: false, err: error.message})})}render() {return (<div><section className="jumbotron"><h3 className="jumbotron-heading">搜索github用戶</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/> <button onClick={this.search}>搜索</button></div></section></div>);}
}export default Search;
setupProxy.js
//react 18版本寫法
const {createProxyMiddleware} = require('http-proxy-middleware')module.exports = function (app) {app.use(createProxyMiddleware('/api1', {target: 'http://localhost:5000',changeOrigin: true,pathRewrite: {'^/api1': ''}}))
}
運行結(jié)果:
5.fetch發(fā)送請求
Search.jsx
import React, {Component} from 'react';
import axios from "axios";
import PubSub from "pubsub-js";class Search extends Component {search = async () => {//連續(xù)結(jié)構+重命名const {keyWordElement: {value: keyWord}} = thisPubSub.publish('atguigu', {isFirst: false, isLoading: true})try {const response = await fetch(`http://localhost:3000/api1/search/users2?q=${keyWord}`)const data = await response.json()console.log(data)PubSub.publish('atguigu', {isLoading: false, users: data.items})} catch (error) {console.log('請求出錯', error)PubSub.publish('atguigu', {isLoading: false, err: error.message})}}render() {return (<div><section className="jumbotron"><h3 className="jumbotron-heading">搜索github用戶</h3><div><input ref={c => this.keyWordElement = c} type="text" placeholder="輸入關鍵詞點擊搜索"/> <button onClick={this.search}>搜索</button></div></section></div>);}
}export default Search;
ajax,fetch,xhr,axios,jquery之間的關系?
?
運行結(jié)果: