NodeJS Go语言、JSON和链码[已关闭]

p5fdfcr1  于 2023-05-17  发布在  Node.js
关注(0)|答案(1)|浏览(117)

已关闭,此问题需要更focused。目前不接受答复。
**想改善这个问题吗?**更新问题,使其仅通过editing this post关注一个问题。

昨天关门了。
Improve this question
我正在尝试解析JSON并解组候选人以创建Election
这些是Go文件中的结构

type Candidate struct {
ID       string \`json:"id"\`
Name     string \`json:"name"\`
School   string \`json:"school"\`
Standing string \`json:"standing"\`
}'

'func (s \*ElectionContract) CreateElection(ctx contractapi.TransactionContextInterface,        electionID string, candidates_received string, startTime string, endTime string) error {

var candidates []Candidate
err := json.Unmarshal([]byte(candidates_received), &candidates)
if err != nil {
    fmt.Printf("Error parsing candidate data. %s\n", err.Error())
    fmt.Printf("candidates_received as bytes: %v\n", []byte(candidates_received))
    return fmt.Errorf("Error parsing candidate data. %s", err.Error())
}

election := Election{
    ID:         electionID,
    Candidates: candidates,
    StartTime:  startTime,
    EndTime:    endTime,
}

electionJSON, err := json.Marshal(election)
if err != nil {
    return fmt.Errorf("Error marshaling election data. %s", err.Error())
}

err = ctx.GetStub().PutState(electionID, electionJSON)
if err != nil {
    return fmt.Errorf("Error saving election data to the ledger. %s", err.Error())
}

return nil

}'

合同适用于HyperLedger Fabric网络网关。这是我在node.js中的代码

'if (fcn === "CreateElection" && args.length === 4) {
if (username === "admin") {
// CreateElection creates a new election on the ledger
//Args are electionID, candidatesJSON, startTime, endTime

var \[electionID, candidates, startTime, endTime\] = args;
// Perform input validation checks
if (!electionID || typeof electionID !== 'string') {
throw new Error('Invalid election ID');
}

            if (!/^Election\d+$/.test(electionID)) {
                throw new Error(\'Please provide an election with the format Election followed by a number\');
            }
            console.log("Successfully passed the election ID test.");
            console.log("Candidates receives are: ", candidates);
            console.log("Successfully passed the Candidates List test.");
            console.log("Successfully converted candidates to JSON string. " + candidates.toString());
            console.log("Start time is: ", startTime);
            // if (!startTime || typeof startTime !== \'string\' || startTime < 0) { // we want it as a string to not be interepreted diff (leading 0 for ex.)
            //     throw new Error('Invalid start time');
            // }

            if (!/^\d{10}$/.test(startTime)) {
                throw new Error('Invalid UNIX timestamp.Please provide a valid numeric end time value greater than the current time in UNIX seconds time (10 digits).');
            }
            console.log("Start time is: ", startTime);
            const currentTimestampMilliseconds = Date.now(); // Get the current timestamp in milliseconds
            const currentTimestampSeconds = Math.floor(currentTimestampMilliseconds / 1000); // Convert milliseconds to seconds

            const bufferSeconds = 300; // Buffer time in seconds (5 minutes)
            const adminTimestampSeconds = startTime + bufferSeconds; // Add the buffer time for the admin

            console.log("Current timestamp in milliseconds is: ", currentTimestampMilliseconds);
            console.log("Current timestamp in seconds is: ", currentTimestampSeconds);
            console.log("Admin timestamp in seconds is: ", adminTimestampSeconds);

            if (currentTimestampSeconds > adminTimestampSeconds) {
                throw new Error('Invalid UNIX timestamp. Please provide a time in the future. We cannot create an election in the past. The current timestamp in seconds is: ' + currentTimestampSeconds);
            }

            console.log("Successfully passed the start time test.");

            // if (!endTime || typeof endTime !== 'string' || endTime < 0) {
            //     throw new Error('Invalid end time');
            // }
            if (!/^\d{10}$/.test(endTime)) {
                throw new Error('Invalid UNIX timestamp. Please provide a valid numeric end time value greater than the current time in UNIX seconds time (10 digits).');
            }
            console.log("End time is: ", endTime);

            const minimumElectionDuration = 3600; // Minimum election duration in seconds (1 hour)
            const duration = endTime - startTime; // Calculate the duration in seconds
            if (duration < minimumElectionDuration) {
                throw new Error('Invalid UNIX timestamp. The election has to last at least 1 hour.');
            }
            console.log("Successfully passed the end time test.");

            // Convert candidates to JSON string
            console.log("Successfully converted candidates to JSON string.");
            console.log("candidates not stringified to JSON ", candidates);

            const parsedCandidates = JSON.stringify(candidates);
            console.log("Parsed candidates:", parsedCandidates);

            result = await contract.submitTransaction(fcn, electionID, parsedCandidates, startTime, endTime);
            await gateway.disconnect();

            result = JSON.parse(result.toString());

            let response = {
                message: message,
                result
            }
            return response;
        } else {
            throw new Error('Only admin can create an election');
        }'

为了可爱的追逐,我立即打印了每一个可能的调试,我有 Postman 发送:'{“fcn”:“CreateElection”,“args”:“[“Election4”,[{“ID”:“id1”,“Name”:“Jake Joe”,“School”:“School of Business”,“Standing”:“Junior”},{“ID”:“id2”,“Name”:“丹尼尔West”,“School”:“School of Business”,“Standing”:“Junior”},{“ID”:“id3”,“Name”:“Josh Sebas”,“School”:“School of Arts and Sciences”,“Standing”:“Senior”}],“1683957147”,“1683987997”]”}“
这就是我收到的:

`"result": "Unexpected token o in JSON at position 1"`

从这里调试出来的。

`channeName is :  mychannel chaincode name is :  evote function requested is :      CreateElection args provided :  [ 'Election4',   [ { ID: 'id1',       Name: 'Jake Joe',           School: 'School of Business',       Standing: 'Junior' },     { ID: 'id2',       Name: 'Daniel     West',       School: 'School of Business',       Standing: 'Junior' },     { ID: 'id3',           Name: 'Josh Sebas',       School: 'School of Arts and Sciences',       Standing: 'Senior' } ],       '1683957147',   '1683987997' ] arg1:  Election4 arg2:  [ { ID: 'id1',     Name: 'Jake Joe',     School: 'School of Business',     Standing: 'Junior' },   { ID: 'id2',     Name: 'Daniel West',     School: 'School of Business',     Standing: 'Junior' },   { ID: 'id3',     Name: 'Josh Sebas',     School: 'School of Arts and Sciences',     Standing: 'Senior' } ] arg3:  1683957147 arg4:  1683987997 Wallet path: /home/azureuser/Desktop/HyperledgerNetwork/NewProject/api-2.0/org1-wallet Successfully passed the election ID test. Candidates receives are:  [ { ID: 'id1',     Name: 'Jake Joe',     School: 'School of Business',     Standing: 'Junior' },   { ID: 'id2',     Name: 'Daniel West',     School: 'School of Business',     Standing: 'Junior' },   { ID: 'id3',     Name: 'Josh Sebas',     School: 'School of Arts and Sciences',     Standing: 'Senior' } ] Successfully passed the Candidates List test. Successfully converted candidates to JSON string. [object Object],[object Object],[object Object] Start time is:  1683957147 Start time is:  1683957147 Current timestamp in milliseconds is:  1683939760822 Current timestamp in seconds is:  1683939760 Admin timestamp in seconds is:  1683957147300 Successfully passed the start time test. End time is:  1683987997 Successfully passed the end time test. Successfully converted candidates to JSON string. candidates not stringified to JSON  [ { ID: 'id1',     Name: 'Jake Joe',     School: 'School of Business',     Standing: 'Junior' },   { ID: 'id2',     Name: 'Daniel West',     School: 'School of Business',     Standing: 'Junior' },   { ID: 'id3',     Name: 'Josh Sebas',     School: 'School of Arts and Sciences',     Standing: 'Senior' } ]     Parsed candidates: [{"ID":"id1","Name":"Jake Joe","School":"School of Business","Standing":"Junior"},{"ID":"id2","Name":"Daniel West","School":"School of Business","Standing":"Junior"},{"ID":"id3","Name":"Josh Sebas","School":"School of Arts and Sciences","Standing":"Senior"}] Getting error: Unexpected end of JSON input message result is: Unexpected end of JSON input`

我真的很想你的投入,我花了很多时间和天试图找到一个解决方案。
PS:当我在初始链代码调用中硬编码时,它确实工作了:\func (s \*ElectionContract) InitLedger(ctx contractapi.TransactionContextInterface) error { unixTimeStart := time.Now().Unix() unixTimeEnd := unixTimeStart + 86400 StartTime := strconv.FormatInt(unixTimeStart, 10) EndTime := strconv.FormatInt(unixTimeEnd, 10)\

elections := []Election{
    Election{
        ID: "e1",
        Candidates: []Candidate{
            Candidate{ID: "c1", Name: "Candidate 1", School: "School of Business", Standing: "Junior"},
            Candidate{ID: "c2", Name: "Candidate 2", School: "School of Arts and Sciences", Standing: "Freshman"},
            Candidate{ID: "c3", Name: "Candidate 3", School: "School of Arts and Sciences", Standing: "Sophomore"},
            Candidate{ID: "c4", Name: "Candidate 4", School: "School of Arts and Sciences", Standing: "Senior"},
            Candidate{ID: "c5", Name: "Candidate 5", School: "School of Business", Standing: "Sophomore"},
            Candidate{ID: "c6", Name: "Candidate 6", School: "School of Architecture and Design", Standing: "Sophomore"},
        },
        
        //EndTime:   time.Now().Unix() + 86400, //One day election
        StartTime: StartTime,
        EndTime: EndTime, //Two minute election
    },
}

for election := range elections {
    electionAsBytes, _ := json.Marshal(election)
    err := ctx.GetStub().PutState("Election"+strconv.Itoa(i), electionAsBytes)

    if err != nil {
        return fmt.Errorf("Failed to put to world state. %s", err.Error())
    }
}

return nil

}'

gjmwrych

gjmwrych1#

这个错误是因为你试图解析不是JSON的东西。
return JSON.parse();
console.log不解析为JSON的结果。
大多数情况下,这似乎是因为实际上没有网关连接。检查您的定义。
这也是支持你没有得到任何信息的合同,等等。channeName是:mychannel chaincode名称为:请求的evote函数为:
我不太明白,但如果在处理结果之前断开网关连接,似乎也会发生这种情况。尝试注解掉gateway.disconnect()行。
最后,尝试使用CLI。它有不同的连接方法。如果它起作用,则所有链码都是正确的,并且通常再次指示连接定义不正确。
一旦正确连接,您应该能够console.log一些有关通道,合同等的信息。

相关问题