0

我有一个 fastify node.js 应用程序,我可以在它返回给调用浏览器 JS 之前看到一个承诺的文本结果。当该承诺返回给浏览器 JS 时,我只能从承诺文本中得到一个空字符串。我假设承诺没有被链接,这是一个没有其他内容的新承诺。如果这是正确的,我将如何访问内部承诺结果?

我已经在 fastify 应用程序的模块之间传递了 Promise,在任何时候都没有问题得到结果,我只是不明白我在这一点上做错了什么。这些是我在通话双方都尝试做的基础知识:

// node.js
fastify.get('/promise', async function(request, reply) {
    var results = await someFunction(request)
    console.log(await results.text()) // this displays results as XML
    return results
})

// call to fastify app from browser JS
async function getPromise(params) {
    var response = await fetch("http://localhost:3000/promise" + params, { mode: 'no-cors' })
    console.log(await response.text()) // this is empty
}
4

1 回答 1

1

{ mode: 'no-cors' } 阻止您访问响应,因为它是不透明

不透明过滤响应是类型为“不透明”的过滤响应,URL 列表为空列表,状态为 0,状态消息为空字节序列,标头列表为空,正文为空。

这里有一个完整的例子:

'use strict'

const fetch = require('node-fetch')
const fastify = require('fastify')({ logger: true })
const fastifyCors = require('fastify-cors')

fastify.register(fastifyCors, {
  credentials: true,
  origin: '*'
})

fastify.get('/promise', async function (request, reply) {
  const results = await fetch('http://www.mocky.io/v2/5e738e46300000fd9b2e66ae')
  return results.text()
})

fastify.listen(3000)

在浏览器中:

await fetch("http://localhost:3000/promise").then(res => res.text())

它会打印HELLO WORLD

于 2020-03-19T15:39:45.963 回答