Code Monkey home page Code Monkey logo

Comments (8)

hylkevds avatar hylkevds commented on September 25, 2024 1

Thanks. I've added the cors.exposed.headers option to the example filter in web.xml

from frost-server.

hylkevds avatar hylkevds commented on September 25, 2024

The reason the service does not directly echo the entire entity is that entities can be very large. In one of our projects we have Observations containing several MBs of data. You can imagine that it would be very inefficient if that data is sent twice for every Observation creation.

Req 36 - create-update-delete/deep-insert-status-code

Upon successfully creating an entity, the service response SHALL contain a Location header that contains the URL of the created entity. Upon successful completion the service SHALL respond with 201 Created.

So that's what the service does. You can parse the entity id from the location header, or request the location header and get the entity id from the response to that. Our java client library does the former.

from frost-server.

tobi238 avatar tobi238 commented on September 25, 2024

Ok, getting the entity id from parsing the location header sounds great.
But actually, I'm not able to get the header when I make a JavaScript POST request in the Browser.
Do you have any idea how to do that?

from frost-server.

hylkevds avatar hylkevds commented on September 25, 2024

That depends on what framework you use to make the POST request...

from frost-server.

tobi238 avatar tobi238 commented on September 25, 2024

I've tried XMLHttpRequest, Jquery Ajax und fetch: The Header isn't available no matter which one I use...

XMLHttpRequest:

var json = JSON.stringify({
    "name": "Temperature Monitoring System",
    "description": "Sensor system monitoring area temperature",
    "properties": {
        "Deployment Condition": "Deployed in a third floor balcony",
        "Case Used": "Radiation shield"
    }
});

var request = new XMLHttpRequest();

request.open("POST", "http://localhost:8080/SensorThingsServer-1.0/v1.0/Things");
request.setRequestHeader("Access-Control-Expose-Headers", "location");
request.onreadystatechange = function () {
    console.log(request.getResponseHeader('location'));
    console.log(request.getAllResponseHeaders());
};
request.send(json);

Jquery Ajax:

var json = JSON.stringify({
    "name": "Temperature Monitoring System",
    "description": "Sensor system monitoring area temperature",
    "properties": {
        "Deployment Condition": "Deployed in a third floor balcony",
        "Case Used": "Radiation shield"
    }
});

$.ajax({
    type: "POST",
    url: baseUrl + `/Things`,
    data: json,
    beforeSend: function (request) {
        request.setRequestHeader("Access-Control-Expose-Headers", 'Location');
    },
    success: function (data, status, xhr) {
        console.log(xhr.getResponseHeader('location'));
    },
    complete: (xhr, status) => {
        console.log(xhr.getAllResponseHeaders());
    }
});

fetch:

var json = JSON.stringify({
    "name": "Temperature Monitoring System",
    "description": "Sensor system monitoring area temperature",
    "properties": {
        "Deployment Condition": "Deployed in a third floor balcony",
        "Case Used": "Radiation shield"
    }
});

const myHeaders = new Headers({
    'Content-Type': 'application/json',
    'Access-Control-Expose-Headers': 'Location'
});

fetch("http://localhost:8080/SensorThingsServer-1.0/v1.0/Things", {
      method: 'POST',
      headers: myHeaders,
      body: json
   }).then((response) => {
      console.log(response.headers.get('location'));
   }).catch((error) => {
      throw `Thing konnte nicht erstellt werden`;
});

from frost-server.

hylkevds avatar hylkevds commented on September 25, 2024

This works for me:

<!DOCTYPE html>
<html>
    <head>
        <title>SensorThings POST Test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    </head>
    <body>
        <div></div>
        <script type="text/javascript">
            'use strict';

            jQuery(function () {
                var json = JSON.stringify(
                        {
                            "name": "Temperature Monitoring System",
                            "description": "Sensor system monitoring area temperature",
                            "properties": {
                                "Deployment Condition": "Deployed in a third floor balcony",
                                "Case Used": "Radiation shield"
                            }
                        }
                );
                jQuery.ajax({
                    type: "POST",
                    url: "http://localhost:8080/SensorThingsService/v1.0/Things",
                    data: json,
                    success: function (data, status, xhr) {
                        console.log(xhr.getResponseHeader('location'));
                    },
                    complete: (xhr, status) => {
                        console.log(xhr.getAllResponseHeaders());
                    }
                });
            });
        </script>
    </body>
</html>

Output:

http://localhost:8080/SensorThingsService/v1.0/Things(273)
location: http://localhost:8080/SensorThingsService/v1.0/Things(273)
date: Tue, 24 Oct 2017 14:23:00 GMT
content-length: 0

from frost-server.

tobi238 avatar tobi238 commented on September 25, 2024

When I run your code I get null for the location header and an empty string for all headers:

null
 

In the Chrome Developer Tools a can see the Response with the location header:

image

from frost-server.

tobi238 avatar tobi238 commented on September 25, 2024

Ok, I solved it. The problem came from the CORS settings in the WEB.INF\web.xml:
I needed to add the following to my cors filter:

<init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Location</param-value>
</init-param>

My complete web.xml file for reference:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
		<init-param>
          <param-name>readonly</param-name>
          <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
	
	
   <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>http://localhost:80, http://localhost:8080, http://localhost:81, http://localhost:8100</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
		<param-value>GET,POST,PATCH,HEAD,DELETE,OPTIONS</param-value>
        </init-param>
        <init-param>
            <param-name>cors.support.credentials</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization</param-value>
        </init-param>
	<init-param>
            <param-name>cors.exposed.headers</param-name>
            <param-value>Location</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

My Function for POSTing new Things and return their ID:

const baseUrl = `http://localhost:8080/SensorThingsServer-1.0/v1.0`
const createThing = () => {
    let thing = {
        "name": "Temperature Monitoring System",
        "description": "Sensor system monitoring area temperature",
        "properties": {
           "Deployment Condition": "Deployed in a third floor balcony",
           "Case Used": "Radiation shield"
        }
    };

    return fetch(`${baseUrl}/Things`, {
        method: 'POST',
        body: JSON.stringify(thing)
    }).then((response) => {
        if (!response.ok) {
            throw response.statusText;
        }
        return parseInt(response.headers.get('location').split('(')
            .filter(function(v){ return v.indexOf(')') > -1})
            .map( function(value) { 
                return value.split(')')[0]
            }).pop());

    }).catch((error) => {
        throw `Thing konnte nicht erstellt werden`;
    });
}

from frost-server.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.