Thrift调用如何返回Struct类型数据?客户端接收结果为undefined问题
Hey there! Let's work through this Thrift Struct return issue you're hitting—super frustrating when the server looks right but the client gets undefined, right?
First: Make sure your server returns a proper Thrift Struct instance
You mentioned the server logs { faculty: 10, submitted: false }, which looks like a plain JavaScript object. But Thrift doesn't serialize plain objects correctly for Struct types—you need to use the auto-generated GAPFStatus class from your Thrift IDL to create the return value.
Here's what the correct server-side code should look like:
// Import the generated Struct class from your Thrift output const { GAPFStatus } = require('./path/to/generated/thrift-code'); // Inside your service method: const buildStatus = () => { const status = new GAPFStatus(); status.faculty = 10; status.submitted = false; return status; // Return the instance, not a plain object! };
If you return a literal object instead of the generated class instance, Thrift's serialization layer can't map it to the Struct definition, which leads to the client getting undefined.
Second: Verify your client is handling the response correctly
Double-check that your client is using the generated code and properly receiving the response. For example:
const { GAPFStatus, YourThriftServiceClient } = require('./path/to/generated/thrift-code'); const thrift = require('thrift'); // Initialize your client (adjust based on your transport/protocol) const client = new YourThriftServiceClient(/* your config */); // Call the service method and handle the result client.yourServiceMethod((err, result) => { if (err) { console.error('Call failed:', err); return; } // Result should be a GAPFStatus instance now console.log('Faculty:', result.faculty); console.log('Submitted:', result.submitted); });
Make sure you're not skipping callback/async-await handling—if you're using promise-based calls, use await properly to capture the return value.
Third: Double-check your Thrift IDL definition
Ensure your service method explicitly returns the GAPFStatus struct in your IDL:
struct GAPFStatus { 1: i32 faculty, 2: bool submitted } service YourService { // Make sure the return type is GAPFStatus, not void! GAPFStatus yourServiceMethod() }
If the return type is accidentally set to void, the client will never receive a value, hence the undefined.
Fourth: Rule out version mismatches
Check that both your server and client are using the same version of the thrift npm package. Version discrepancies can break serialization/deserialization, leading to lost data between server and client.
内容的提问来源于stack exchange,提问作者abrarisme

