2017-07-05 34 views
0

所以我有一個後端服務在端點https://sample.herokuapp.com/上的Heroku上運行。我想POST以下JSON對象到/bug/端點:Ionic 3 - POST數據到Heroku端點

{ 
    "email": "[email protected]", 
    "name": "Anthony", 
    "text": "Test Bug", 
    "picture": "Empty" 
} 

如果我在失眠發佈此數據郵差,它完美的作品,並返回解析信息的HTML響應。然而,發帖時使用下面的代碼在離子3這個數據,

sendMail(type:string, text:string):void { 
      this.nativeStorage.getItem('sample').then((sample) => { 
        var data = new Object(); 
        data["name"] = sample.name 
        data["email"] = sample.email; 
        data["picture"] = sample.picture; 
        data["text"] = text; 

        this.db.object('/general/sample').take(1).subscribe((sample) => { 
         var xhr = new XMLHttpRequest(); 
         var endpoint = sample.address + sample.endpoints[type]; 

         xhr.addEventListener("readystatechange", function() { 
         if (this.readyState === 4) { 
          console.log("Got response: " + this.responseText); 
         } 
        }); 

         xhr.open("POST", endpoint); 
         xhr.setRequestHeader("Accept", "application/json"); 
        xhr.setRequestHeader("Content-Type", "application/json"); 
         console.log("sample sending: " + JSON.stringify(data, undefined, 2)); 
         console.log("sample endpoint: " + endpoint); 

        xhr.send(JSON.stringify(data)); 
        }) 
      }) 
    } 

我收到以下錯誤日誌中的Heroku:

2017-07-05T17:02:24.707431+00:00 heroku[router]: at=info method=OPTIONS path="/bug" host=sample.herokuapp.com request_id=5e679c8e-cac7-4ff2-9277-dec80a250c11 fwd="150.108.242.198" dyno=web.1 connect=1ms service=3ms status=200 bytes=215 protocol=https 

我已經做了很多的研究對這個問題,我相信這是一個CORS問題。但是,我嘗試使用Access-Control-Allow-...標頭來解決此問題,但收到相同的錯誤。

我已經安裝了Cordova whitelist插件,並在我的index.html中包含了meta標籤。

這是一個相當複雜的問題,所以我很感謝所有的幫助!

+1

只是想知道爲什麼不使用角度的HTTP對象?我有代碼與heroku交談,我沒有問題。我設置我的控制器來注入Http對象,並在我的方法中使用它來進行其他調用。 – getbuckts

+0

感謝您的建議,但我試過HttpModule,而且我仍然在Heroku中收到同樣的問題。任何想法,爲什麼這可能是? –

回答

1

在heroku一側你有Cors配置?

var app = express(); 
/* cors conig */ 
var corOptions = { 
    "origin": "*", 
    "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", 
    "preflightContinue": true, 
    allowedHeaders: 'Content-Type,Authorization,X-Requested-With' 
} 
app.use(cors(corOptions)); 

我CORS的依賴: 「CORS」: 「^ 2.8.1」

+0

這是爲我做的。非常感謝! –