N
N
Novel2015-02-05 00:29:38
Node.js
Novel, 2015-02-05 00:29:38

How to send an array of strings to the client?

I'm trying to pass an array of strings cities to the client.
Error: "first argument must be a string or Buffer"
What content-type to choose and in what form is it better to pass?

request.on('data', function(chunk) {
      recData = chunk;

      response.writeHead(200, {"Content-Type": "application/x-javascript"});
     			response.write(cities);
     			response.end();
    });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kazmiruk, 2015-02-05
@losaped

Redo
response.write(cities);
on
response.write(JSON.stringify(cities));
since response.write only accepts strings and a buffer. That is, the data must first be serialized.
Well, in this case it is better to change Content-type from application/x-javascript to application/json

A
Alexander Prozorov, 2015-02-05
@Staltec

...
      response.json(cities);
...

The json() method will automatically set the content-type to 'application/json'. And the HTTP status is always 200 by default. It can be omitted explicitly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question