为什么我在本地节点的响应中没有得到JSON对象。js / express服务器吗?

时间:2022-12-01 15:58:25

-- The background to situation --

——情境背景—

I'm making an e-form signup for a client of our business marketing strategy service blah blah blah...

我正在为我们的商业营销策略服务的客户做电子表单注册等等……

the form is done and looks great. now I need to hook it up to the existing API of the service our business uses to hold/sort/query/etc the submitted information.

表单完成了,看起来很棒。现在我需要将它连接到我们的业务用于保存/排序/查询/等所提交信息的服务的现有API。

I'm a very junior developer and the API is very complex. I just want to make sure my ES6/javascript is in proper working order. The ajax calls are working, no bugs in my code etc. So it seemed the quickest easiest thing to do in order to test things was just make a simple local server so I can test my calls get everything working BEFORE I start going through tons of API documentation and getting it properly hooked up to our service. The first call seems to work fine. But I couldn't get my lil' baby server to "respond" properly with some static info to parse through. I'm primarily a front-end developer, but I'm obsessed with figuring this little server problem out at this point... So help would be VERY appreciated.

我是一个初级开发人员,API非常复杂。我只是想确认我的ES6/javascript是否正常工作。ajax调用是工作,没有bug的代码等。看来最快最容易的事情为了测试只是做一个简单的本地服务器我可以测试调用完成所有的工作在我开始经历大量的API文档,正确连接到我们的服务。第一个电话似乎很管用。但我无法让lil的baby服务器用一些静态信息“响应”以进行解析。我主要是一个前端开发人员,但我现在痴迷于解决这个小服务器问题……因此,我们非常感谢您的帮助。

-- the fetch request --

——取回请求—

fetch('http://localhost:4000/send-zip')
            .then( 
                (response) => {
                    response.json(),
                    console.log('begin fetch to local server'),
                    console.log(response),
                    populate_store_selector(response)
                })
            .catch(
                (error)=> console.log('basic fetch request failed' + error)
            )

-- that other function in case people ask --

另一个函数

(it is simply meant to iterate through and populate an html input type="select" )

(它只是用来迭代并填充html输入类型="select")

function populate_store_selector(arg) {
    for (i of arg) {
        let new_option = document.createElement('option')
        new_option.innerHTML = arg[i]
        select_shop.appendChild(new_option)
    }
}

-- my little baby server --

——我的婴儿服务器

const express = require('express')
const server = express()

server.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

server.get('/send-zip', function (req, res) {
    res.send({ "options": ['option1', 'option2', 'option3'] })
})

server.listen(4000, () => console.log('mock server listening on port 4000!'))

the server works just fine and does it's job OTHER than I'm never able to get it to send a JSON object back :( I've tried lots of things so far. Honestly it doesn't matter as my request on the front end works just fine but I'm too obsessed to let this go right now...

这台服务器工作得很好,而且它还能正常工作,但我无法让它发送回一个JSON对象:(到目前为止,我已经尝试了很多东西。)老实说,这并不重要,因为我对前端的要求很好,但我太沉迷于此,现在就放手……

-- what the console.log() shows in the browser --

log()在浏览器中显示的内容。

begin fetch to local server

main.js:104 

Response {type: "cors", url: "http://localhost:4000/send-zip", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: trueheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "cors"url: "http://localhost:4000/send-zip"__proto__: Response

main.js:108 

basic fetch request failedTypeError: arg is not iterable

1 个解决方案

#1


2  

You might try parsing the response after the response stream completes, and then taking action on the data.

您可以尝试在响应流完成后解析响应,然后对数据采取操作。

fetch('http://localhost:4000/send-zip')
        .then( 
            (response) => {
                return response.json();
        }).then(
            (response_json) => {
                console.log('begin fetch to local server'),
                console.log(response_json),
                populate_store_selector(response_json)
            })
        .catch(
            (error)=> console.log('basic fetch request failed' + error)
        )

The reason that you need to include the additional .then step and return response.json() is that the http response object returns the body data as a readable stream.

需要包含附加的then步骤和返回response.json()的原因是http response对象将主体数据作为可读流返回。

The JSON function is designed to accept a stream and convert it into JSON after the stream completes. This may feel somewhat unintuitive for anyone familiar with axios or other AJAX convenience libraries, as that part of the process is abstracted from view.

JSON函数设计为接受流并在流完成后将其转换为JSON。对于任何熟悉axios或其他AJAX便利库的人来说,这可能有点不直观,因为流程的这一部分是从视图中抽象出来的。

What this basically means is that after you wait for the response http object to be returned, you need to wait again for the stream to also complete.

这基本上意味着,在等待响应http对象返回后,您需要再次等待流也完成。

There are a few different methods available which can act upon a stream upon completion including arrayBuffer,blob, and text (there are a few more I think as well). Usually they tend to convert the data into the format you prefer after it has completed.

有一些不同的方法可以在完成后对流进行操作,包括arrayBuffer、blob和text(我还认为还有一些)。通常他们倾向于在数据完成后将其转换为您喜欢的格式。

#1


2  

You might try parsing the response after the response stream completes, and then taking action on the data.

您可以尝试在响应流完成后解析响应,然后对数据采取操作。

fetch('http://localhost:4000/send-zip')
        .then( 
            (response) => {
                return response.json();
        }).then(
            (response_json) => {
                console.log('begin fetch to local server'),
                console.log(response_json),
                populate_store_selector(response_json)
            })
        .catch(
            (error)=> console.log('basic fetch request failed' + error)
        )

The reason that you need to include the additional .then step and return response.json() is that the http response object returns the body data as a readable stream.

需要包含附加的then步骤和返回response.json()的原因是http response对象将主体数据作为可读流返回。

The JSON function is designed to accept a stream and convert it into JSON after the stream completes. This may feel somewhat unintuitive for anyone familiar with axios or other AJAX convenience libraries, as that part of the process is abstracted from view.

JSON函数设计为接受流并在流完成后将其转换为JSON。对于任何熟悉axios或其他AJAX便利库的人来说,这可能有点不直观,因为流程的这一部分是从视图中抽象出来的。

What this basically means is that after you wait for the response http object to be returned, you need to wait again for the stream to also complete.

这基本上意味着,在等待响应http对象返回后,您需要再次等待流也完成。

There are a few different methods available which can act upon a stream upon completion including arrayBuffer,blob, and text (there are a few more I think as well). Usually they tend to convert the data into the format you prefer after it has completed.

有一些不同的方法可以在完成后对流进行操作,包括arrayBuffer、blob和text(我还认为还有一些)。通常他们倾向于在数据完成后将其转换为您喜欢的格式。