简体   繁体   中英

How to set status code 201 in Javascript?

I'm new to Javascript and I'm currently trying to set status code as 201 in headers but I'm getting 200. I want to set headers 201 and print success response else some fault error msg but it's not working as expected. Below is the code which I have tried:

var sm = require("service-metadata");
var hm = require("header-metadata");
var headers = hm.current;

var querystring = require("querystring");
var uri = sm.getVar("var://service/URI");

var data = querystring.parse(uri.split("?")[1]);
var response = {
  data: [
    {
      id: "02",
      Details: [
        {
          errorMessage: "Success",
          errorCode: 201,
        },
      ],
    },
  ],
};
var Error = {
  ErrorDetails: {
    Reason: "Fault",

    errorMessage: "Runtime Error",
  },
};
if (response.statusCode == 201) session.output.write(response);
else {
  session.output.write(Error);
}

The code you have here, as written, is checking for a value that doesn't exist. Thus it's always printing the "Error" object.

// response.statusCode doesn't exist in your response object,
// so it is equal to "undefined" instead of 201 or 200.
// this condition will never be true.
if (response.statusCode == 201)

Based on the way you've created your response object, you should be doing this:

if (response.data[0].Details[0].errorCode == 201)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM