JavaScript エプソンレシートプリンターと通信するには?

ショコラ
ショコラ

JavaScript エプソンレシートプリンターと通信するには?

https://{デバイス名}/cgi-bin/epos/service.cgi に HTTPS でアクセスに成功!
CORS に悩まされました。
きっとここからなんかするんです。

もっさん先輩
もっさん先輩

service.cgi にアクセスするには↓こう書きます。

// エプソンレシートプリンターで通信できるところ
const url = 'https://epsonc6ca09/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000'
const postdata = `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print"></epos-print></s:Body></s:Envelope>`

// XMLHttpRequest バージョン
const xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-Type','text/xml charset=utf-8')
xhr.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT')
xhr.setRequestHeader('SOAPAction', '""')
xhr.timeout = 10000
xhr.onreadystate
xhr.onreadystatechange = function(){
  if (xhr.readyState === XMLHttpRequest.DONE) { // 通信が完了したとき
    if (xhr.status === 200) {
      console.log(`通信成功 ${xhr.responseText}`)
    }
    else {
      console.error(`通信エラー ${xhr.status}`)
    }
  }
}
xhr.send(postdata)

fetchバージョン

// fetch バージョン
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type':'text/xml charset=utf-8',
    'If-Modified-Since':'Thu, 01 Jun 1970 00:00:00 GMT',
    'SOAPAction':'""',
  },
  body: postdata
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok ' + response.statusText)
  }
  return response.text() // ここでレスポンスをテキスト形式で取得
})
.then(data => {
  console.log(`通信成功 ${data}`)
})
.catch(error => {
  console.error(`通信エラー ${error}`)
})

以上

Scroll to Top