2025-07-29

Ionic 的筆記:Ionic 要連線 Web Request

本文內容都是以 Ionic + Vue 為前題撰寫


根據Ionic 官方的說明《Working around CORS in a server you can’t control》,直接使用 JS 的 XMLHttpRequest 或是 fetch API 會有 CROS 的問題

所以建議使用 CapacitorHttp API 來處理

CapacitorHttpfetch 很像,用法如下:

<script setup lang="ts">
import { CapacitorHttp, HttpResponse } from '@capacitor/core'

function login(userName, password){
	CapacitorHttp.post({
		url: 'https://example.com/login', 
		headers: {
			'Content-Type': 'application/json'
		},
		data: JSON.stringify({user: userName, password: password})
	}).then(function(rsrp: HttpResponse){
		if (rsrp.status == 200) {
			return rsrp.data;
		} else {
			throw "無法登入,請輸入帳號密碼";
		}
	})
}

</script>

另外,如果要使用 CapacitorHttp API,記得設置 config(參見CapacitorHttp API 的 config 範例

以下是一個 config 範例(capacitor.config.ts)

import type { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
	appId: 'com.foo.bar',
	appName: 'Ion-Foo-Bar',
	webDir: 'dist',
	plugins: {
		// 加上以下 plugin
		CapacitorHttp: {
			enabled: true
		}
	}
}

export default config;

沒有留言:

張貼留言