前言
java语言在多数时,会作为一个后端语言,为前端的php,node.js等提供API接口。前端通过ajax请求去调用java的API服务。今天以node.js为例,介绍两种跨域方式:CrossOrigin和反向代理。
一、准备工作
pom.xml:
4.0.0 com.example spring-boot-150.0.1-SNAPSHOT jar spring-boot-15 Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent1.5.3.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-devtoolsruntime org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
pom.xml
App.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
User.java
package com.example;
public class User {
public int id;
public String name;
public int age;
}
MainController.java:
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MainController {
@GetMapping("findAllUser")
public List findAllUser() {
List list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
User user = new User();
list.add(user);
user.id = i;
user.name = "name_" + i;
user.age = 20 + i;
}
return list;
}
}
项目结构如下图所示:
访问http://localhost:8080/findAllUser
使用HBuilder创建node.js express项目:
选择ejs模板引擎:
index.ejs文件代码如下:
<%= title %> <%= title %>Welcome to <%= title %>
| {{row.id}} | {{row.name}} | {{row.age}} |
通过angular.js的http方法调用api请求
右键运行项目:
运行效果:
发现调用ajax请求时跨域失败。
二、spring boot后台设置允许跨域
这时,修改MainController类,在方法前加@CrossOrigin注解:
@RestController
public class MainController {
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("findAllUser")
public List findAllUser() {
List list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
User user = new User();
list.add(user);
user.id = i;
user.name = "name_" + i;
user.age = 20 + i;
}
return list;
}
}
这是声明findAllUser方法允许跨域,
也可以修改App.java,来实现全局跨域:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
var proxy = require('express-http-proxy');
var apiProxy = proxy('http://localhost:8080', {});
app.use('/api', apiProxy);
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
修改index.ejs文件:
var app = angular.module('app', []);
app.controller('MainController', function($rootScope, $scope, $http) {
$http({
method: 'GET',
url: '/api/findAllUser'
}).then(function successCallback(r) {
$scope.rows = r.data;
});
});
完整的index.ejs文件如下:
<%= title %>
<%= title %>
Welcome to
<%= title %>
| {{row.id}} | {{row.name}} | {{row.age}} |
运行效果如下:
总结
第二种通过反向代理的方式是最佳方案。在正式项目中,可以使用node.js控制web前端渲染与spring boot后端提供API服务的组合。这样,可以控制用户在node.js端登录后才能调用spring boot的API服务。在大型web项目中也可以使用node.js的反向代理,把很多子站点关联起来,这样便发挥出了网站灵活的扩展性。
以上所述是小编给大家介绍的spring boot ajax跨域的两种方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



