2017-07-26 85 views
0

我不明白,我應該怎麼做專法javascrpt例如:如何在javascript中實現loopback CURL?

curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d "{ 
    \"name\": \"GreatNight\", 
    \"city\": \"Tehran\" 
}" "http://localhost:3000/api/CoffeeShops" 

怎麼可能是這個樣子的代碼在JavaScript?

+2

cURL不適用於Javascript。如果你在談論客戶端(瀏覽器)JS,那麼你想要的是一個AJAX請求。你可以谷歌數以百計的例子如何做到這一點。如果你在說node.js,那麼看看這裏:https://stackoverflow.com/questions/6819143/curl-equivalent-in-nodejs。附:不確定你在這種情況下通過「回送」引用了什麼? – ADyson

+0

@adyson,謝謝。我想在移動應用中使用crud api,這是實現b,離子和使用打字稿/ JavaScript和角度。 – RSA

+0

您可能需要了解更多關於node.js的信息https://www.npmjs.com/package/curl。 – Parsaria

回答

1

與jQuery ajax

$.ajax({ 
    type: 'POST', 
    url: "http://localhost:3000/api/CoffeeShops", 
    data: { 
    name: "GreatNight", 
    city: "Tehran" 
    }, 
    dataType: "json", 
    accepts: { 
    text: "application/json" 
    } 
}); 
+0

謝謝,但我不認爲jQuery和Ajax將解決我在Ionic App中的問題。 – RSA

1

這是解決方案:

HTML

<ion-content> 
    <ion-list> 
    <ion-item> 
     <ion-label fixed> shop name </ion-label> 
     <ion-input type="text"[(ngModel)]="name" > </ion-input> 
    </ion-item> 

    <ion-item> 
     <ion-label fixed> city </ion-label> 
     <ion-input type="text" [(ngModel)]="city"> </ion-input> 
    </ion-item> 

    <ion-item> 
     <button ion-button block large (click)="post()">post </button> 
    </ion-item> 

    </ion-list> 

</ion-content> 

page2.ts

import { Component } from '@angular/core'; 
import { Http, Headers, RequestOptions } from '@angular/http'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/operator/toPromise'; 

import { NavController, NavParams } from 'ionic-angular'; 

@Component({ 
    selector: 'page-page2', 
    templateUrl: 'page2.html' 
}) 
export class Page2 { 
    public name; 
    public city; 
    constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) { } 

post(){ 
let headers = new Headers(
{ 
    'Content-Type' : 'application/json' 
}); 
let options = new RequestOptions({ headers: headers }); 

let data = JSON.stringify({ 
    name:this.name, 
    city:this.city 
}); 
console.log(data); 
let url = 'http://localhost:3000/api/CoffeeShops'; 
return new Promise((resolve, reject) => { 
    this.http.post(url, data, options) 
    .toPromise() 
    .then((response) => 
    { 
    console.log('API Response : ', response.json()); 
    resolve(response.json()); 
    }) 
    .catch((error) => 
    { 
    console.error('API Error : ', error.status); 
    console.error('API Error : ', JSON.stringify(error)); 
    reject(error.json()); 
    }); 
}); 
} 

} 
+0

嗨@Reza,幹得好。 – Parsaria