I have a problem when use HTTP post method in the following code:
let body = JSON.stringify(applicationLink);
let requestHeaders = new Headers();
var headers = new Headers();
headers.set('Content-Type', ['application/json']);
headers.set('Access-Control-Allow-Origin', ['*']);
let reqoptions = new RequestOptions({
headers: headers
});
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,reqoptions).map(res => res.json())
When I execute the code I see an error:
XMLHttpRequest cannot load http..... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http....' is therefore not allowed access.
Request Method:OPTIONS is mde instead of post
Request URL:http://localhost:7001/workprocess-service/resources/links
Request Method:OPTIONS
Status Code:200 OK
Remote Address:[::1]:7001
Response Headers
view source
Allow:OPTIONS,POST,GET,HEAD
Content-Type:application/vnd.sun.wadl+xml
Date:Thu, 26 May 2016 11:10:25 GMT
Last-Modified:Thu, 26 May 2016 09:02:27 CEST
Transfer-Encoding:chunked
Vary:Accept
X-Powered-By:Servlet/3.0 JSP/2.2
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:access-control-allow-origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:7001
Origin:http....
Referer:http....
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
and my data is not linked to the request.
If I remove reqoption
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body).map(res => res.json())
the request is a POST but i receive an error 415 ( Unsupported Media Type)
Request URL:http://localhost:7001/workprocess-service/resources/links
Request Method:POST
Status Code:415 Unsupported Media Type
Remote Address:[::1]:7001
Response Headers
view source
Connection:close
Content-Length:22
Content-Type:text/html; charset=UTF-8
Date:Thu, 26 May 2016 11:14:44 GMT
X-Powered-By:Servlet/3.0 JSP/2.2
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:48
Content-Type:text/plain;charset=UTF-8
Host:localhost:7001
Origin:http:....
Referer:http:.....
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
Request Payload
view source
{labelFR: "dsds", labelNL: "dsds", url: "dsds"}
labelFR
:
"dsds"
labelNL
:
"dsds"
url
:
"dsds"
My data is linked to the request
You need to make your server set the header Access-Control-Allow-Origin because you are sending a CORS "Cross Origin Resource Sharing" request. Which simply means you are sending the request to a url that's not the same as the url you are sending from.
I see your backend is servlet/3.0, you can enable CORS "for all origins" by adding a web filter
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
#WebFilter(urlPatterns = {"*"})
public class CORSFilter implements Filter{
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
}
Related
I am trying to disable the caching on on the the pages. The reason - the page in question should display up to date data on each request and the data is coming from external XML feed.
I am using standard HttpWebRequest HttpWebResponse. All is working fine but I am getting some (I believe) caching issues where by querying XML feed URL directly I am getting more up to date data compared to my Controller/View data which uses the same URL.
XML feed URL is appended with random numbers on each request and Caching was disabled in the controller ([OutputCache(NoStore = true, Duration = 0)]) as well as in the ActionResult, which produces the following:
Response
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.1
X-AspNet-Version: 4.0.30319
X-Frame-Options: SAMEORIGIN
X-Powered-By: ASP.NET
X-UA-Compatible: IE=edge
Date: Thu, 04 Aug 2016 13:22:33 GMT
Content-Length: 75285
Request
pretty print
GET /investor-relations/share-price HTTP/1.1
Host: cms.crestnicholson-dev.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: ecos.dt=1470316952533; ASP.NET_SessionId=5lbh4v20kac0boadibjfwedr; IsAgreeToCookiePolicy=true
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
And still outdated/cached data is rendered on the pageā¦
If someone has any ideas/suggestions, It would be greatly appreciated.
Controller code:
[OutputCache(NoStore = true, Duration = 0)]
public class InvestorRelationsController : Controller
{
public ActionResult SharePrice()
{
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
return PartialView(GetSharePrice());
}
private SharePriceModel GetSharePrice()
{
try
{
var xml = GetSharePriceXml();
return ParseSharePrice(xml);
}
catch (Exception)
{
return new SharePriceModel() {IsServiceUnavailable = true};
}
}
private SharePriceModel ParseSharePrice(string xml)
{
Guard.ArgumentNotNull(xml, "xml");
var model = new SharePriceModel();
var doc = new XmlDocument();
doc.Load(new StringReader(xml));
var root = doc.DocumentElement;
model.DateLastUpdated = root.SelectSingleNode("Time").InnerText;
model.Price = root.SelectSingleNode("CurrentPrice").InnerText;
model.Change = root.SelectSingleNode("Change").InnerText;
model.ChangePersentage = root.SelectSingleNode("PercentageChange").InnerText;
return model;
}
private string GetSharePriceXml()
{
Uri address = new Uri(SiteConfiguration.SharePriceFeedUrl);
Random random = new Random();
string url = address + "?random=" + random.Next();
// Set a default policy level for the "http:" and "https" schemes.
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
// Create the web request
var request = WebRequest.Create(url) as HttpWebRequest;
// Set type to POST
request.CachePolicy = noCachePolicy;
request.KeepAlive = false;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Cache-Control", "private");
// Get response
using (var response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
using (var reader = new StreamReader(response.GetResponseStream()))
{
// Console application output
return reader.ReadToEnd().Trim();
}
}
}
}
I want to get json data from the server(tomcat server)
I was import "package:http/http.dart' as http".
But, Result is "The built-in library 'dart: io' is not available on Dartium" in Datium console.
So "dart build" and run the "Uncaught Unsupported operation: Platform._version" error comes in chrome console.
Also, dart: html and dart: io's "HttpRequest" was using the request fails.
How can I get response data from the server(tomcat or another was)?
Thanks your answer!!!
import 'dart:async';
import "dart:html";
import "dart:convert";
import 'package:http/http.dart' as http;
final ButtonElement loginButton = querySelector("#login");
void main() {
loginButton.onClick.listen((e) {
requestTest2IO();
});
}
void requestTest2IO(){
var url = 'server url';
http.get(url, headers : {'Cookie': 'JSESSIONID : xxxxxxxxxxxxxxxxxxxxxx',
'User-Agent': 'xxxxxxx',
'x-app-stat-json': '(Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36,appversion=8}'
})
.then((response) {
List<String> repos = JSON.decode(response.body);
print(repos);
});
}
I have the following client-side code:
import 'dart:html';
import 'dart:async';
void main() {
WebSocket ws = new WebSocket('ws://127.0.0.1:4949');
ws.onOpen.listen((_) => print('open'));
ws.onMessage.listen((MessageEvent e) => print(e.data));
ws.onClose.listen((_) => print('closed'));
ws.onError.listen((_) => print('error'));
}
And this server-side code:
import 'dart:io';
import 'dart:async';
main() {
ServerSocket.bind('127.0.0.1', 4949).then((ServerSocket server) {
server.listen((Socket client){
print('Connection from '
'${client.remoteAddress.address}:${client.remotePort}');
client.write('hello from server');
});
});
}
The WebSocket connection connects successfully to the ServerSocket. The server code prints:
Connection from 127.0.0.1:55516
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:4949
Origin: http://127.0.0.1:3030
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: PrJr2iVElmEsX7ZItHnWHA==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.39 (Dart) Safari/537.36
The problem is that the onOpen and onMessage do not get triggered. I suspect I'm missing something but not sure what.
Yes you are missing something, the complete server side implementation. ServerSocket is just a plain socket used for TCP (or UDP).
But a websocket requires a HTTP server, that does the handling of the HTTP request and that upgrades the connection to a Websocket connection:
import 'dart:io';
void main() {
HttpServer.bind('127.0.0.1', port)
.then((HttpServer server) {
print('listening for connections on $port');
server.listen((HttpRequest request) {
if (request.uri.path == '/ws') {
WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
websocket.listen((message) => print('Message from client'));
print('Client connected');
});
} else {
/* ... */
}
});
},
onError: (error) => print("Error starting HTTP server: $error"));
}
A simple example from SethLadd. But I would probably do also a check if the requests CONNECTION and UPGRADE headers are correct before upgrading to a websocket. After upgrading the connection you have a Websocket instance that is similar to the on one the client side.
I'm unable to successfully download a file from the server using a Web API get call. The download seems to start but then Chrome throws:
"Resource interpreted as Document but transferred with MIME type application/zip"
Firefox doesn't say that but the download still fails.
What am I doing wrong in the following setup?:
[HttpGet, Route("api/extractor/downloadresults")]
public HttpResponseMessage DownloadResultFiles()
{
int contentLength = 0;
this.ResultFiles.ForEach(f => contentLength = contentLength + f.FileSize);
var streamContent = new PushStreamContent((outputStream, httpContext, transportContent) =>
{
...zip files...
});
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
streamContent.Headers.ContentLength = contentLength;
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "result.zip"
};
var response = Request.CreateResponse();
response.StatusCode = HttpStatusCode.OK;
response.Content = streamContent;
}
I trigger the download via:
window.location.href = "api/extractor/downloadresults";
With the resulting headers:
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:ASP.NET_SessionId=ibwezezeutmu2gpajfnpf41p
Host:localhost:47384
Referer:http://localhost:47384/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Response Headers
Cache-Control:no-cache
Content-Disposition:attachment; filename=result.zip
Content-Length:436102
Content-Type:application/zip
Date:Mon, 16 Dec 2013 22:36:31 GMT
Expires:-1
Persistent-Auth:true
Pragma:no-cache
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcbmV3VG9vbGJveFxUb29sYm94XFRvb2xib3guV2ViXGFwaVx0ZXJtZXh0cmFjdG9yXGRvd25sb2FkcmVzdWx0ZmlsZXM=?=
Have you tried changing the request headers, for example the accept header?
Also, here you can find a similar question, some of the solutions suggested there may help you.
ASP.Net MVC 3 RTM. I am trying to use the OutputCache attribute in an action, but doesn't appear to be working. Here is the Http Request and Response.
Request URL:http://localhost/MyApp/Employee.mvc/GetImage?userId=myUserId
Request Method:GET
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:ASP.NET_SessionId=sessionIdStuff
Host:localhost
Pragma:no-cache
Referer:http://localhost/MyApp/Employee/Review/1/Index
User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)
AppleWebKit/534.13 (KHTML, like Gecko)
Chrome/9.0.597.98 Safari/534.13
Query String Parameters
userId:myUser
Response Headers
Cache-Control:private, no-store, max-age=3484
Content-Length:1428
Content-Type:image/jpeg
Date:Wed, 16 Feb 2011 22:59:14 GMT
Expires:Wed, 16 Feb 2011 23:57:19 GMT
Last-Modified:Wed, 16 Feb 2011 22:57:19 GMT
Server:Microsoft-IIS/5.1
Vary:*
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Powered-By:ASP.NET
Here is the controller:
[HttpGet, OutputCache(Location= OutputCacheLocation.Client, VaryByParam="userId", Duration=3600, NoStore=true)]
public FileContentResult GetImage(string userId)
{
byte[] result;
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultCredentials;
result = client.DownloadData(string.Format(IntranetUrl, userId));
}
return File(result, "image/jpeg");
}
and my View:
<img alt="Employee Picture" src='#Url.Action("GetImage", "Employee", new { userId = Model.UserId, area=""})' width="75px" height="100px" />
I tried comparing with other static images that are getting cached and the only differences where these lines:
Cache-Control:private, no-store,
max-age=3484
This is included in my action, but not in the static images. Also, the static images had an ETag, but my action response did not.
Can anyone help why this might not be cached in the browser?
Thanks for any help..
Try remove: NoStore=true (or set NoStore = false), and it'll work :)