我讀了很多關於「訪問控制 - 允許 - 來源」問題的論壇。大多數論壇都要求使用dataType:'jsonp',但是通常jsonp會打到GET請求,我想要做POST請求。最終GET請求也不起作用。訪問控制 - 允許 - 源錯誤發送一個jQuery發佈
其實我將iPhone應用程序轉換爲PhoneGap,所以重新編寫客戶代碼到HTML-5 & Jquery mobile。我試圖打的網址在Objective-C中效果很好。
這裏是Objective-C代碼
NSString *username=[self urlEncodeValue:[userNameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString *password=[self urlEncodeValue:[passWordField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
NSString *params = [[NSString alloc] initWithFormat:@"username=%@&password=%@",username,password];
NSData *paramData = [params dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[params release];
NSString *paramsLength = [NSString stringWithFormat:@"%d", [paramData length]];
NSString *urlString=[[NSString alloc] initWithFormat:@"%@?",[dict valueForKey:@"LoginAuthentication"]];
NSURL *authURL = [NSURL URLWithString:urlString];
[urlString release];
NSHTTPURLResponse *authenticationResponse= nil;
NSMutableURLRequest *authenticationRequest = [NSMutableURLRequest requestWithURL:authURL];
[authenticationRequest setHTTPMethod:@"POST"];
[authenticationRequest setValue:paramsLength forHTTPHeaderField:@"Content-Length"];
[authenticationRequest setHTTPBody:paramData];
NSError *error = nil;
int errorCode;
NSData *responseData = [NSURLConnection sendSynchronousRequest:authenticationRequest
returningResponse:&authenticationResponse
error:&error];
if ([authenticationResponse respondsToSelector:@selector(allHeaderFields)]) {
//success
}
上面的代碼工作得很好。
這裏是我轉換爲JavaScript代碼這給「訪問控制允許來源」錯誤
$(document).ready(function() {
$.ajax({
type: "POST",
crossDomain: true,
//dataType:'jsonp',
//callback: '?',
url : "https://externalserver.com/loginAuth?",
data : {'username' : 'username', 'password' : 'password'},
success : function (response) {
alert('login failed');
},
error: function(e){
console.log(e);
}
});
});
我試着用GET/POST請求,並試圖運行一些本地服務器這個本地文件。什麼都沒有
我收到以下錯誤消息
的XMLHttpRequest無法加載https://externalserver.com/loginAuth? Access-Control-Allow-Origin不允許原始位置爲null。
XMLHttpRequest無法加載https://externalserver.com/loginAuth? Access-Control-Allow-Origin不允許原始位置爲null。
您是否將網址添加到白名單? –
是的,我已經在白名單中添加了網址。順便說一句,我在瀏覽器中出錯。 – gviswanathan
當你在瀏覽器中發現這個錯誤時,你是通過服務器訪問你的網頁還是直接從你的電腦打開html文件? – Romain