espruino / Espruino

The Espruino JavaScript interpreter - Official Repo
http://www.espruino.com/
Other
2.79k stars 747 forks source link

Http get - following redirects from next.js API #2200

Closed solidogen closed 2 years ago

solidogen commented 2 years ago

I'm trying to connect to REST api written using next.js api routes.

I'm getting permanent redirection response to the same page, but browser handles this gracefully and fetches the data.

In browser dev tools it doesn't look like there are any redirects at all.

How can I replicate this behavior in espruino code? Calling the same page always gets me 301. I tried using Connection: keep-alive but it doesn't do anything I guess.

Simplest reproducer:

let appConfig = require('./app-config')
let wifi = require('Wifi')
let httpClient = require('http')

const ssid = appConfig.default.ssid
const wifiPassword = appConfig.default.wifiPassword

const getDiodeStatusEndpoint = 
  'https://tt-robot.netlify.app/api/diode' // (301, netlify hosting)
// 'https://table-tennis-robot-web.vercel.app/api/diode' // (308, vercel hosting)
// 'https://www.att.com/' // (also built with next.js, 301)

function fetchDiodeStatus() {
  var requestOptions = url.parse(getDiodeStatusEndpoint, false)
  httpClient.get(requestOptions, function (res) {
    var responseBody = ''

    res.on('data', function (data) {
      console.log('\nHTTP:\n' + data) // current output -> HTTP: Redirecting to https://table-tennis-robot-web.vercel.app/api/diode (308)
      responseBody += data
    })
    res.on('close', function (hadError) {
      console.log('\nFull response body: ' + responseBody)
    })
    res.on('error', function (data) {
      console.log('\nResponse error::\n' + data)
    })
  })
}

function connectToWifi() {
  wifi.setHostname('esp-tt')
  wifi.connect(ssid, { password: wifiPassword }, function (err) {
    console.log('connected? err=', err, 'info=', wifi.getIP())
    fetchDiodeStatus()
  })
  wifi.save()
}

connectToWifi()
gfwilliams commented 2 years ago

What device are you using? Is it possible it doesn't support HTTPS so is trying an HTTP request, and so is getting the redirect?

solidogen commented 2 years ago

Hmm that makes sense.

I'm using NodeMCU v3

gfwilliams commented 2 years ago

Yes, that's do it... NodeMCU is ESP8266 which I'm pretty sure doesn't do HTTPS with Espruino - I think we found there wasn't enough RAM for Espruino and HTTPS

solidogen commented 2 years ago

Thanks, I resolved this by hosting my server on Heroku, which allows http connections, unlike Netlify and Vercel :+1: Now device can successfully fetch data from https://tt-robot-web.herokuapp.com/api/diode

Turned out next.js had nothing to do with the issue itself.