簡單摸索了 React + TypeScrip 由於沒有新項目要用到,就開始摸一下node,今天寫個hello world分享一下過程。(默認安裝了node)javascript
先引入http: 使用createServer方法建立一個服務器,端口爲:8080,js代碼以下:html
const http = require('http');
http.createServer((req, res) => {
console.log('啓動:127.0.0.1:8080');
res.end('hello world');
}).listen(8080);
console.log('啓動完成');
複製代碼
文件建立完成後,你找到你的demo.js文件並在node環境下啓動它:前端
node demo.js
java
如今已經啓動了本地服務器,能夠在瀏覽器上驗證一下,打開 127.0.0.1:8080:node
瀏覽器上打印出來咱們的 hello world,終端上也打印出了咱們的 console.logreact
恭喜,驗證成功~!!跨域
這樣很清晰的看出來 res.end() 方法裏面就是咱們返回給前端的參數。瀏覽器
這裏咱們用剛剛學到的react來發出一個請求:服務器
import React from 'react';
class demo extends React.Component {
constructor(props) { //構造函數
super(props);
this.state = {
mytext: '',
}
}
getData() {
//請求數據函數
fetch(`http://127.0.0.1:8080`,{
method: 'POST',
}).then(res => res.text()).then(
data => {
this.setState({mytext:data})
}
)
}
componentWillMount() {
this.getData();
}
render() {
return(
<div> <div>{this.state.mytext}</div> </div>
);
}
}
export default demo;
複製代碼
咱們向剛剛啓動的127.0.0.1:8080發出一個請求,可是能夠看到報錯了:函數
這個是咱們常常遇到的跨域問題,解決方法很簡單,就是在咱們的服務端加上容許訪問:
const http = require('http');
http.createServer((req, res) => {
console.log('啓動:127.0.0.1:8080');
res.writeHead(200,
{
'Content-Type':'text/html',
'Access-Control-Allow-Origin': '*', // 容許跨域訪問
'Access-Control-Allow-Headers': '*', // 容許訪問
}
);
res.end('hello world');
}).listen(8080);
console.log('啓動完成');
複製代碼
再訪問就能夠到數據已經返回來了:
咱們在前端請求時加上訪問參數 name: 'demo':
import React from 'react';
class demo extends React.Component {
constructor(props) { //構造函數
super(props);
this.state = {
mytext: '',
}
}
getData() {
//請求數據函數
fetch(`http://127.0.0.1:8080`,{
method: 'POST',
// 加入參數
body: JSON.stringify(
{name: 'demo'}
)
}).then(res => res.text()).then(
data => {
this.setState({mytext:data})
}
)
}
componentWillMount() {
this.getData();
}
render() {
return(
<div> <div>{this.state.mytext}</div> </div>
);
}
}
export default demo;
複製代碼
服務端代碼:
const http = require('http');
http.createServer((req, res) => {
console.log('啓動:127.0.0.1:8080');
res.writeHead(200,
{
'Content-Type':'text/html',
'Access-Control-Allow-Origin': '*', // 容許跨域訪問
'Access-Control-Allow-Headers': '*', // 容許訪問
}
);
let post = '';
req.on('data', (chunk) => {
post += chunk;
})
req.on('end', () => {
res.end(post);
})
}).listen(8080);
console.log('啓動完成');
複製代碼
建立一個 post 用來存放前端傳出來的參數,使用 req.on('data') 獲取,req.on('end') 則是處理和輸出。
瀏覽器輸出:
const http = require('http');
http.createServer((req, res) => {
console.log('啓動:127.0.0.1:8080');
res.writeHead(200,
{
'Content-Type':'text/html',
'Access-Control-Allow-Origin': '*', // 容許跨域訪問
'Access-Control-Allow-Headers': '*', // 容許訪問
}
);
let post = '';
req.on('data', (chunk) => {
post += chunk;
})
req.on('end', () => {
// 把單引號改成雙引號
post = JSON.parse(post.replace(/'/g, '"'));
// 檢查響應代碼,檢查正文是否爲空,確保它是有效的JSON
if(res.statusCode === 200) {
if(post.name === 'demo') {
res.end(JSON.stringify(post));
} else {
res.end('沒有該接口');
}
} else {
res.end('訪問失敗');
}
})
}).listen(8080);
console.log('啓動完成');
複製代碼
當前端參數 name 不爲 demo 時接口返回錯誤信息~
這裏我就不打印出來,但願大家本身試一下咯。