반응형
Node.js의 JSON 객체로 응답 (객체 / 배열을 JSON 문자열로 변환)
저는 백엔드 코드에 대한 초보자이고 JSON 문자열에 응답하는 함수를 만들려고합니다. 나는 현재 예제에서 이것을 가지고 있습니다.
function random(response) {
console.log("Request handler 'random was called.");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("random numbers that should come in the form of json");
response.end();
}
이것은 기본적으로 "JSON 형식으로 제공되어야하는 임의의 숫자"문자열을 인쇄합니다. 내가 원하는 것은 숫자에 관계없이 JSON 문자열로 응답하는 것입니다. 다른 콘텐츠 유형을 입력해야합니까? 이 함수는 그 값을 클라이언트 측에서 말하는 다른 사람에게 전달해야합니까?
당신의 도움을 주셔서 감사합니다!
Express와 함께 res.json 사용 :
function random(response) {
console.log("response.json sets the appropriate header and performs JSON.stringify");
response.json({
anObject: { item1: "item1val", item2: "item2val" },
anArray: ["item1", "item2"],
another: "item"
});
}
또는 :
function random(response) {
console.log("Request handler random was called.");
response.writeHead(200, {"Content-Type": "application/json"});
var otherArray = ["item1", "item2"];
var otherObject = { item1: "item1val", item2: "item2val" };
var json = JSON.stringify({
anObject: otherObject,
anArray: otherArray,
another: "item"
});
response.end(json);
}
var objToJson = { };
objToJson.response = response;
response.write(JSON.stringify(objToJson));
당신이 경우 alert(JSON.stringify(objToJson))
당신은 얻을 것이다{"response":"value"}
JSON.stringify()
노드가 사용하는 V8 엔진에 포함 된 기능 을 사용해야 합니다.
var objToJson = { ... };
response.write(JSON.stringify(objToJson));
편집 : 내가 아는 한, IANA 는 RFC4627application/json
에서 와 같이 JSON에 대한 MIME 유형을 공식적으로 등록했습니다 . 여기에있는 인터넷 미디어 유형 목록에도 나열 됩니다 .
Express.js 3x 이후 응답 객체에는 모든 헤더를 올바르게 설정하는 json () 메서드가 있습니다.
예:
res.json({"foo": "bar"});
익스프레스에는 애플리케이션 범위의 JSON 포맷터가있을 수 있습니다.
express \ lib \ response.js를 살펴본 후 다음 루틴을 사용하고 있습니다.
function writeJsonPToRes(app, req, res, obj) {
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
res.set('Content-Type', 'application/json');
var partOfResponse = JSON.stringify(obj, replacer, spaces)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
var callback = req.query[app.get('jsonp callback name')];
if (callback) {
if (Array.isArray(callback)) callback = callback[0];
res.set('Content-Type', 'text/javascript');
var cb = callback.replace(/[^\[\]\w$.]/g, '');
partOfResponse = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + partOfResponse + ');\n';
}
res.write(partOfResponse);
}
반응형
'developer tip' 카테고리의 다른 글
SpringData : "delete by"가 지원됩니까? (0) | 2020.09.02 |
---|---|
UIAlertAction에 대한 핸들러 작성 (0) | 2020.09.02 |
Laravel Homestead 사용 : '지정된 입력 파일 없음' (0) | 2020.09.02 |
약속 체인에서 setTimeout 사용 (0) | 2020.09.02 |
Chrome 확장 프로그램 첫 실행 / 업데이트 감지 (0) | 2020.09.02 |