• Follow me :

Javascript new Response Tutorial (With Examples)

Javascript new Response Tutorial (With Examples)
  1. Basic Text Response:

    You can create a simple text response like this:

    javascript
    const text = "Hello, World!"; const response = new Response(text, { status: 200, statusText: "OK", headers: { "Content-Type": "text/plain" } });
  2. JSON Response:

    To send JSON data as a response:

    javascript
    const jsonData = { message: "Success", data: { id: 123, name: "John" } }; const response = new Response(JSON.stringify(jsonData), { status: 200, statusText: "OK", headers: { "Content-Type": "application/json" }, });
  3. HTML Response:

    If you want to return an HTML response:

    javascript
    const html = "<html><body><h1>Welcome to my website</h1></body></html>"; const response = new Response(html, { status: 200, statusText: "OK", headers: { "Content-Type": "text/html" } });
  4. Custom Headers:

    You can include custom headers in your response:

    javascript
    const text = "Custom Headers Example"; const headers = new Headers(); headers.append("Custom-Header", "Some Value"); const response = new Response(text, { status: 200, statusText: "OK", headers });
  5. Error Response:

    To send an error response with a specific HTTP status code (e.g., 404 Not Found):

    javascript
    const errorMessage = "Resource not found"; const response = new Response(errorMessage, { status: 404, statusText: "Not Found", headers: { "Content-Type": "text/plain" } });

These are some basic examples of using the Response constructor to create various types of HTTP responses in JavaScript. You can customize the status code, status text, headers, and response content to suit your needs.

Share this article