You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Java与Node.js REST服务互调及传参示例代码需求

没问题!我给你整理了Node.js和Java REST服务双向调用的完整示例,包含请求对象传递、解析和结果返回的全流程,直接就能参考着跑起来~

双向REST调用示例:Node.js ↔ Java

1. Node.js 调用 Java REST API

第一步:搭建Java REST服务(Spring Boot)

先从Java端的API写起,用Spring Boot实现最方便:

1.1 定义请求/响应对象

// RequestMessage.java
public class RequestMessage {
    private String content;

    // 必须保留无参构造器,方便JSON反序列化
    public RequestMessage() {}

    public RequestMessage(String content) {
        this.content = content;
    }

    // Getter和Setter
    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

// ResponseResult.java
public class ResponseResult {
    private String processedContent;
    private boolean success;

    public ResponseResult(String processedContent, boolean success) {
        this.processedContent = processedContent;
        this.success = success;
    }

    // Getter和Setter
    public String getProcessedContent() {
        return processedContent;
    }

    public void setProcessedContent(String processedContent) {
        this.processedContent = processedContent;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }
}

1.2 编写REST Controller

// MessageController.java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MessageController {

    @PostMapping("/api/message/process")
    public ResponseResult processMessage(@RequestBody RequestMessage request) {
        // 模拟业务处理:给原消息添加前缀
        String processed = "Java处理结果:" + request.getContent();
        return new ResponseResult(processed, true);
    }
}

启动Spring Boot服务后,默认端口是8080,接口地址为 http://localhost:8080/api/message/process

第二步:Node.js 端调用Java API

我们用axios库发送POST请求,先安装依赖:

npm install axios

然后编写调用代码:

// node-call-java.js
const axios = require('axios');

async function callJavaApi() {
    try {
        // 构造要传递的消息对象
        const requestData = {
            content: "来自Node.js的消息"
        };

        // 发送POST请求到Java接口
        const response = await axios.post('http://localhost:8080/api/message/process', requestData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });

        // 解析并打印响应结果
        console.log("Java返回的处理结果:", response.data.processedContent);
        console.log("请求是否成功:", response.data.success);
    } catch (error) {
        console.error("调用Java API失败:", error.message);
    }
}

// 执行调用
callJavaApi();

运行文件:node node-call-java.js,就能看到Java返回的处理结果啦。


2. Java 调用 Node.js REST API

第一步:搭建Node.js REST服务(Express)

先安装依赖:

npm install express body-parser

然后编写接口代码:

// java-call-node.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// 解析JSON格式的请求体
app.use(bodyParser.json());

// 定义接收消息的接口
app.post('/api/message/handle', (req, res) => {
    // 解析请求对象中的字符串消息
    const incomingMessage = req.body.content;
    console.log("收到Java的消息:", incomingMessage);

    // 模拟业务处理:给原消息添加后缀
    const processed = incomingMessage + " —— Node.js处理完成";

    // 返回处理结果
    res.json({
        processedContent: processed,
        success: true
    });
});

// 启动服务
app.listen(port, () => {
    console.log(`Node.js服务运行在 http://localhost:${port}`);
});

启动服务:node java-call-node.js,接口地址为 http://localhost:3000/api/message/handle

第二步:Java 端调用Node.js API

我们用Spring的RestTemplate发送请求,先配置Bean:

// RestTemplateConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

然后编写调用代码(可以放在Controller或测试类里):

// NodeApiCaller.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

public class NodeApiCaller {

    @Autowired
    private RestTemplate restTemplate;

    public void callNodeApi() {
        // 构造请求对象
        RequestMessage request = new RequestMessage("来自Java的消息");

        // 发送POST请求到Node.js接口
        String nodeApiUrl = "http://localhost:3000/api/message/handle";
        ResponseResult response = restTemplate.postForObject(nodeApiUrl, request, ResponseResult.class);

        // 输出处理结果
        if (response != null && response.isSuccess()) {
            System.out.println("Node.js返回的处理结果:" + response.getProcessedContent());
        } else {
            System.out.println("调用Node.js API失败");
        }
    }
}

可以在Spring Boot启动类里测试调用:

// Application.java
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner run(NodeApiCaller caller) {
        return args -> caller.callNodeApi();
    }
}

启动Spring Boot服务后,控制台就会输出Node.js返回的处理结果。


小提示

  • 确保两个服务端口不冲突(示例中Java用8080,Node.js用3000)
  • 生产环境需要配置CORS解决跨域问题,开发测试阶段可以暂时忽略
  • 示例异常处理比较简单,实际项目建议完善超时、重试等逻辑

内容的提问来源于stack exchange,提问作者user13683799

火山引擎 最新活动