Reputation: 798
I am using below code for post method request in ionic 2.
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
let body = new FormData();
body.append('UserName', 'sp');
body.append('password', 's');
let options = new RequestOptions({ headers: headers })
this.http
.post('http://192.168.1.9:8080/api/Restaurant/Login', body, options)
.map(res => res.json())
.subscribe(
data => {
console.log("Response is ::::::",data);
},
err => {
console.log("ERROR!::::: ", err);
}
);
Above http://192.168.1.9:8080/api/Restaurant/Login is my local URL. With this URL i am able to get request / response from iOS simulator and postman but not from ionic 2 project.
I am getting error as per attached screenshot.
Server side we added below CORS headers.
<httpprotocol>
<customheaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customheaders>
</httpprotocol>
Can any one help where i am wrong?
Thank you in advance.
Upvotes: 1
Views: 820
Reputation: 681
On your sever side, do you have WebSecurity configured? My experience with angular is that it sends a pre-flight OPTIONS request before the actual request is sent, if your sever doesn't support OPTIONS requests then it will reject it. I'm not sure if this will help you as it's set in Spring.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.....
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/**/user").permitAll()
...
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll() //This allows options requests
...
}
All the best! Hope you can succeed :) Happy coding
Upvotes: 1