[SOLVED] Meteor.fetch / prerender.io

I automatically submit a list of URLs to prerender.io on server startup and am refactoring to use Meteor.fetch. This was working fine before and works fine with ‘curl’, and I see nothing odd about the request/response, but I’m getting a response “invalid json response body” at <…prerender API URL…> Unexpected end of json input.

By some chance does this ring any bells for anyone? I’ve spent too much time on this already and I thought I’d try here.

async function _doPost(url, data, opts) {
	opts = {...opts, body: JSON.stringify(data)}
	try {
		const response = await fetch(url, opts)
		return response.json()
	} catch(err) {
		console.error(`Failed to request PrerenderIO re-cache for url "${url}"; error:`, err)
	}
}

const doPost = Meteor.wrapAsync(_doPost)

urls.forEach(url => {
	 const targetUrl = "https://api.prerender.io/recache"

	 const options = {
		 method: 'POST',
		 mode: 'no-cors',
		 cache: 'no-cache',
		 referrerPolicy: 'no-referrer',
		 headers: new Headers({
			 'Content-Type': 'application/json',
		 }),
	 }

	 const data = {
		 "prerenderToken": Meteor.settings.PrerenderIO.token,
		 url,
	 }

	 const result = doPost(targetUrl, data, options)
})

Meteor version is 2.5.5. Thanks for any help!

Figured it out BTW. The problem was two-fold. For one, Response.json() returns a Promise and needs an await before it in my case.

Also, response.json() can fail in some cases, even if response.getHeader(‘content-type’) == ‘application/json’; I’m not sure what the problem was there, but a thread I found recommends converting using Response.text() anyway as that always works and converting to JSON is just another call.

1 Like