微服务-node.js

权威解释

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

解决跨域问题

本地文件(使用 jquery Ajax请求)

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="jquery.js"></script>
</head>
<body>
<script>
   $.ajax({
       url:'http://localhost:8081',
       type: 'get',

       success: function (res) {
       console.log(res);
       },error:function (res) {     
       }

   })
</script>
</body>
</html>

index.js(服务器文件)

var express = require('express');

var app = express();

var bodyParser = require('body-parser');
//解决跨域的经典方法。不加这个就会存在跨域问题。
app.all('*',function (req, res, next) {

   res.header('Access-Control-Allow-Origin', '*');

   res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

   res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
   if (req.method == 'OPTIONS') {
       res.send(200);
   }
   else {
       next();
   }

});
//  主页输出 "Hello World"
app.get('/', function (req, res) {
   console.log("主页 GET 请求");
   res.send('Hello GET');
})


//  POST 请求
app.post('/', function (req, res) {
   console.log("主页 POST 请求");
   res.send('Hello POST');
})

//  /del_user 页面响应
app.get('/del_user', function (req, res) {
   console.log("/del_user 响应 DELETE 请求");
   res.send('删除页面');
})

//  /list_user 页面 GET 请求
app.get('/list_user', function (req, res) {
   console.log("/list_user GET 请求");
   res.send('用户列表页面');
})

// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/ab*cd', function(req, res) {   
   console.log("/ab*cd GET 请求");
   res.send('正则匹配');
})


var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("应用实例,访问地址为 http://%s:%s", host, port)

})

跨域是违背同源策略的。同源指的是域名,协议,端口号都相同。

node作为中转服务器(demo)

拦截请求,将请求转发到后台,获取后台的返回结果。
后台用Spring Boot。关键代码如下:

package org.springframework.gs_rest_service;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

通过http://localhost:8089/greeting和获得返回结果:
{“id”:4,”content”:”Hello, World!”}

发送HTTP请求了。有一个简单的工具可以用,Simplified HTTP request client,可以比较方便的模拟请求。
node中转服务端的代码修改如下:

var express = require('express');
var request = require('request');

var app = express();

var bodyParser = require('body-parser');
//解决跨域的经典方法。不加这个就会存在跨域问题。
app.all('*',function (req, res, next) {

   res.header('Access-Control-Allow-Origin', '*');

   res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

   res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
   if (req.method == 'OPTIONS') {
       res.send(200);
   }
   else {
       next();
   }

});
//  主页输出 "Hello World"
app.get('/', function (req, res) {
   console.log("主页 GET 请求");
    request('http://localhost:8089/greeting', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) ;// Show the HTML for the baidu homepage.
    res.send(body);
  }
})

})


//  POST 请求
app.post('/', function (req, res) { 

   console.log("主页 POST 请求");
   res.send('Hello POST');
})

//  /del_user 页面响应
app.get('/del_user', function (req, res) {
   console.log("/del_user 响应 DELETE 请求");
   res.send('删除页面');
})

//  /list_user 页面 GET 请求
app.get('/list_user', function (req, res) {
   console.log("/list_user GET 请求");
   res.send('用户列表页面');
})

// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/ab*cd', function(req, res) {   
   console.log("/ab*cd GET 请求");
   res.send('正则匹配');
})


var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port

  console.log("应用实例,访问地址为 http://%s:%s", host, port)

})

本地文件修改如下:

<body>
<div id="test" ></div>
<script>
   $.ajax({
       url:'http://localhost:8081',
       type: 'get',
       success: function (res) {        document.getElementById("test").innerText = res;
       },error:function (res) {     
       }
   })
</script>
</body>

通过本地文件发起请求,运行结果如下:
这里写图片描述

错误是由于搜狗浏览器本身的问题,在火狐和IE11下没有问题。可能是浏览器对谷歌的扩展存在问题。

猜你喜欢

转载自blog.csdn.net/helloworlddm/article/details/80380849