Невозможно взаимодействовать с узлами в Интернете с помощью углового приложения - PullRequest
1 голос
/ 20 апреля 2019

Я сослался на аккредитив cordapp cordapp, который делает то же самое, я скопировал содержимое dist и поместил его в ресурс, но когда я запускаю свой весенний сервер в моем cordapp и перехожу к порту моего узла, я не вижу, может ли пользовательский интерфейс помочь кому-либо помочь относительно этого.

Я получаю ошибку 404, как-то мой порт выбирается моим угловым приложением. Я использовал window.location.href, чтобы взаимодействовать с моим незащищенным интерфейсом API в моем cordapp и использовать динамический 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)
    }

вот мой угловой файл app.route.ts 6:

    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);

Целевая страница содержит пользовательский интерфейс, который я должен видеть при взаимодействии с моими узлами

вот мой сервисный файл:

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();
    }
   );
   }

Я вызываю эту функцию getAllTrades из раздела ngoninit класса app.component.ts, но при вводе этого URL я получаю ошибку http 404. я запустил эту команду и скопировал содержимое папки dist в папку ресурсов моего приложения ng build --prod --aot --build-optimizer Что-то я делаю не так?

...