无法通过角度应用与网络上的节点进行交互

问题描述 投票:1回答:1

我引用了信用证cordapp cordapp,它执行的操作相同,我复制了dist内容并将其放置在资源中,但是当我在cordapp中启动spring服务器并导航到节点的端口时,我看不到ui,任何人都可以提供有关这个。

我收到404错误,我的有角度的应用程序以某种方式获取了我的端口,我使用window.location.href与我的cordapp中暴露的api进行交互,并利用动态url,因为有3个节点,并且所有节点都有不同的端口。

这是Corda api文件的内容:

@RestController
@RequestMapping("/api/trading/") // The paths for GET and POST requests are relative to this base path.
class MainController(rpc: NodeRPCConnection) {

    companion object {
        private val logger = LoggerFactory.getLogger(RestController::class.java)
    }

    private val myLegalName = rpc.proxy.nodeInfo().legalIdentities.first().name
    private val proxy = rpc.proxy

    /**
     * Returns the node's name.
     */
    @GetMapping(value = "me", produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun whoami() = mapOf("me" to myLegalName)

    /**
     * Returns all parties registered with the network map service. These names can be used to look up identities using
     * the identity service.
     */
    @GetMapping(value = "peers", produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun getPeers(): Map<String, List<CordaX500Name>> {
        val nodeInfo = proxy.networkMapSnapshot()
        return mapOf("peers" to nodeInfo
                .map { it.legalIdentities.first().name }
                //filter out myself, notary and eventual network map started by driver
                .filter { it.organisation !in (SERVICE_NAMES + myLegalName.organisation) })
    }

    /**
     * Displays all IOU states that exist in the node's vault.
     */
    @GetMapping(value = "trades", produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun getTrades() : ResponseEntity<List<StateAndRef<TradeState>>> {
        return ResponseEntity.ok(proxy.vaultQueryBy<TradeState>().states)
    }

    /**
     * Initiates a flow to agree an IOU between two parties.
     *
     * Once the flow finishes it will have written the IOU to ledger. Both the lender and the borrower will be able to
     * see it when calling /spring/api/ious on their respective nodes.
     *
     * This end-point takes a Party name parameter as part of the path. If the serving node can't find the other party
     * in its network map cache, it will return an HTTP bad request.
     *
     * The flow is invoked asynchronously. It returns a future when the flow's call() method returns.
     */

    @PostMapping(value = "create-trade", produces = arrayOf("text/plain"), headers = arrayOf("Content-Type=application/x-www-form-urlencoded"))
    fun createIOU(request: HttpServletRequest): ResponseEntity<String> {
        val counter = request.getParameter("counterParty")
        val tradeStatus = request.getParameter("tradeStatus")
        val userId = request.getParameter("userId")
        val assetCode = request.getParameter("assetCode")
        val orderType = request.getParameter("orderType")
        val txDate = request.getParameter("transactionDate")
        val sdf = SimpleDateFormat("dd/MM/yyyy")
        val transactionDate = sdf.parse(txDate)
        val transactionAmount = request.getParameter("transactionAmount").toDouble()
        val transactionFees = request.getParameter("transactionFees").toDouble()
        val transactionUnits = request.getParameter("transactionUnits").toDouble()
        val transactionPrice = request.getParameter("transactionAmount").toDouble()
        val transactionId = request.getParameter("transactionId")
        if (counter == null) {
            throw IllegalArgumentException("Query parameter 'Counter partyName' missing or has wrong format")
        }
        if (transactionAmount <= 0 ) {
            throw IllegalArgumentException("Query parameter 'Transaction Amount' must be non-negative")
        }
        val partyX500NameCounter = CordaX500Name.parse(counter)
        val counterParty = proxy.wellKnownPartyFromX500Name(partyX500NameCounter) ?:
        throw IllegalArgumentException("Target string \"$counter\" doesn't match any nodes on the network.")

        val producer = Producer()
        return try {
            val signedTx = proxy.startTrackedFlowDynamic(TradeFlow.Initiator::class.java,tradeStatus,counterParty,userId,assetCode,orderType,transactionAmount,transactionFees,transactionUnits,transactionId,transactionDate,transactionPrice).returnValue.getOrThrow()
            val mapper = JacksonSupport.createNonRpcMapper()
            val result = mapper.writeValueAsString(signedTx)
            producer.send(result)
            ResponseEntity.status(HttpStatus.CREATED).body("Transaction id ${signedTx.id} committed to ledger.\n")
        } catch (ex: Throwable) {
            logger.error(ex.message, ex)
            producer.send(ex.toString())
            ResponseEntity.badRequest().body(ex.message!!)
        }
    }

    /**
     * Displays all IOU states that only this node has been involved in.
     */
    @GetMapping(value = "getTrade", produces = arrayOf(MediaType.APPLICATION_JSON_VALUE))
    fun getTransactionDetails(@RequestParam("linearID") linearID: String): ResponseEntity<List<StateAndRef<TradeState>>>? {
        if (linearID == null) {
            ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Linear Id cannot be null.\n")
        }
        val idParts = linearID.split('_')
        val uuid = idParts[idParts.size - 1]
        val criteria = QueryCriteria.LinearStateQueryCriteria(linearId = listOf(UniqueIdentifier.fromString(uuid)),status = Vault.StateStatus.ALL)
        return ResponseEntity.ok(proxy.vaultQueryBy<TradeState>(criteria=criteria).states)
    }

这是我的角度6 app.route.ts文件:

    import { LandingPageComponent } from './Landing-Page/landing-page/landing-page.component';
    import { Routes, RouterModule } from "@angular/router";


    const APP_ROUTES:Routes=[
        {
             path:'', component: LandingPageComponent
         }
    ]


export const APP_ROUTES_PROVIDER = RouterModule.forRoot(APP_ROUTES);

登录页面具有与节点交互时应看到的ui内容

这是我的服务文件:

import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';
import { Subject } from 'rxjs';


@Injectable()
export class CordaContentService {
  payload;
  constructor(private http:Http) { }

  private trades = new Subject<any>();

  // Observable string streams
  tradeMethodCalled$ = this.trades.asObservable();

  getAllTrades() {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.get('http://localhost:50005/api/trading/trades',{
     headers: headers
   }).pipe(map((res : any)=>res.json()))
   .subscribe(
    (res) => {
     this.payload = res;
     console.log('success');
     this.trades.next();
    }
   );
   }

我从app.component.ts类的ngoninit部分调用此getAllTrades函数,但是当我输入此URL时,出现http 404错误。我运行此命令并将dist文件夹内容复制到我的cordapp资源文件夹中ng build --prod --aot --build-optimizer我在做错什么吗?

angular corda
1个回答
0
投票
根据上述信息和评论,我认为您可能在angular应用程序中使用了错误的网址。

[通常,如果您的Spring服务器正确启动并调用正确的API,您将不会看到404页面未找到的错误消息。

我建议您在此处查看示例:https://github.com/corda/samples-kotlin/blob/master/Advanced/obligation-cordapp/clients/src/main/kotlin/net/corda/training/server/MainController.kt

© www.soinside.com 2019 - 2024. All rights reserved.