一、Node官網下載pkg安裝包,點擊安裝便可,安裝包包含nodejs和npm(node package manager)
二、安裝完成後,在命令終端輸入html
curl http://npmjs.org/install.sh | sh
三、這個npm.js其實是Node.js的套件管理工具,執行完成以後咱們繼續執行命令,更新npm:前端
sudo npm update npm -g
四、查看npm是否安裝成功vue
npm -v
建立node 服務和web 端通訊須要用到http、https
若是訪問文件須要用到fsnode
一、新建一個文件server.js
二、引入對應所需的依賴ios
var http=require('http'); var https = require('https') var fs = require('fs');
三、建立http 服務web
const server = http.createServer((req, res) => { // 這裏能夠設置header信息, 如跨域等信息 }).listen(8090)
四、啓動服務npm
以上內容便可啓動服務,能夠經過node 的命令啓動服務,默認域名是 http://127.0.0.1:8090
便可訪問node 服務,能夠對建立的服務添加一些監聽
request 監聽有兩個參數,req 請求 和 res 響應
添加監聽的方法, 如文件的請求,方法接口的請求json
const requestHandle = (req, res) => { // 設置一些 請求處理的方法 if (url === '/index') { // 文件的請求 res.writeHead(200, { 'Content-Type': 'text/html' }) fs.readFile('index.html', 'utf8', function (err, data) { if (err) throw err res.end(data) }) } else if (url === '/api') { // 接口請求 req.on('data', function (pamas) { console.log('8888888') // 在此作一些數據的處理 }) req.on('end', () => { // 請求結束 }) } else { // 404 請求 res.write('404') res.end() } }
添加監聽axios
server.on('request', requestHandle)
console.log 的內容均在服務終端上會展現出來api
以釘釘報警爲例,因爲前端不支持直接請求釘釘報警接口,須要經過服務來轉發請求,便有了以下例子
const dingdingHandle = (str, callback) => { // 釘釘報警傳參 const postData = { msgtype: "text", text: { content: str }, "at": { "atMobiles": [ "155********" ], "isAtAll": false } }; const options = { hostname: 'oapi.dingtalk.com', path: '/robot/send?access_token=d529ae67dcc82157032c3c84bad0c450a2329692adca0e00000efcbddf2898', method: 'POST', headers: { 'Content-Type': 'application/json;charset=UTF-8', } }; const req = https.request(options, (res) => { console.log(`狀態碼: ${res.statusCode}`); console.log(`響應頭: ${JSON.stringify(res.headers)}`); res.setEncoding('utf8'); res.on('data', (chunk) => { console.log(`響應主體: ${chunk}`); callback(chunk) }); res.on('end', () => { console.log('響應中已無數據。'); }); }); req.on('error', (e) => { console.error(`請求遇到問題: ${e.message}`); }); // 寫入數據到請求主體 req.write(JSON.stringify(postData)); req.end(); }
這個方法在接收到對應的請求時調用
在服務端request 監聽的回調中對應的接口中調用
... } else if (url === '/api') { // 接口請求 req.on('data', function (params) { console.log('8888888') // 請求釘釘報警接口,並將響應返回的參數推到前端頁面的請求中 dingdingHandle(params.toString, (data) => { res.end(data) }) }) req.on('end', () => { // 請求結束 }) } else { // 404 請求 ...
前端頁面請求,業務場景是頁面報錯時監聽
window.onerror = function (msg, url, line, column, error) { let data = { msg: msg, url: url, line: line, col: column } console.log(data, '--------------'); let xhr = new XMLHttpRequest() // xhr.withCredentials = true xhr.open('POST', 'http://127.0.0.1:8090/api', true) xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(JSON.stringify(data)) xhr.onreadystatechange = function () { xhr.readyState === 4 && xhr.status === 200 && console.log('ok', xhr.responseText) } }
當前前端頁面的服務爲http://127.0.0.1:8080/,和node 服務存在跨域,此時須要在建立服務的時候,添加header 設置
const server = http.createServer(function(req,res) { res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Oring', 'http://127.0.0.1:8080/') res.setHeader('Access-Control-Allow-Credentials', true) }).listen(8090);
注意:
若是是vue 項目中的axios, 須要手動設置header 以及強轉化傳輸的數據
import axios from 'axios' import qs from 'qs' axios({ method: 'post', url: 'http://127.0.0.1:8090/api', data: errorData, withCredentials: false, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: [sdata => { // 強轉數據格式 console.log(sdata, qs.stringify(sdata)) return qs.stringify(sdata) }] }).then(res => { console.log('res=>', res) })