APIGEE api working in rest client , but not in ajax call

Not applicable

I have written APIGEE api, which takes 3 header parameter and json data in body. Its post service. The api is working fine in rest client, but when I am calling it from ajax call, its failing.And headers are missing in APIGEE Trace.

Client side AJAX code:


var jsonObj1=	'{"AGENT_CODE": "1","appName":"apname","appVersion":"1.0" }';




$.ajax({
					type: "POST",
					url:"https://serverIP/dev/sample?CLASS=sample", //APIGEE dev
					
					cache: false,
				
					 header:{
						 'Access-Control-Allow-Origin':'*',
						 'appName':'appnam',
						 'appVersion':'1.0',
						 'Content-Type':'application/json'
						 },

					dataType: "json",
					data: jsonObj1,
					async:false,
					crossDomain:true,
					success: function(result,status,xhr){
					
						var jj=(xhr.status).toString();
						console.log('jj- '+jj);
						if(jj=='200')
						{
						
							console.log("GetSite Successful");
							resultArray =result;
							document.getElementById("result4").innerHTML="result="+JSON.stringify(resultArray);
						}	
					},
					
					error: function(xhr,status,error){
						console.log(" Error is- "+ xhr.status +" "+ error);
						
					}
				});
	
	
	});
	



FROM APIGEE PORTAL:

Request Headers
Accept 	*/*
Accept-Encoding 	gzip,deflate,br
Accept-Language 	en-US,en;q=0.9
Access-Control-Request-Headers 	content-type
Access-Control-Request-Method 	POST
Content-Length 	0
Host 	<IP>:9001
Origin 	http://evil.com/
User-Agent 	Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/67.0.3396.99 Safari/537.36
X-Forwarded-For 	<ip>
X-Forwarded-Port 	443
X-Forwarded-Proto 	https
Request Content
Body


0 11 1,055
11 REPLIES 11

@Chaitanya Bilaware , Welcome to Apigee Community !

It's not an Apigee Problem. It's the CORS issue what you see. But, Apigee can solve the problem since you have full control of Request / Response.

See here how to CORS Enable your API using Apigee Edge 4MV4D video,

-------------------------------

Anil Sagar

5997-screen-shot-2017-11-23-at-75916-pm.png Learn Apigee Concepts in 4 Minutes HandsOn using 150+ 4 Minute Videos

I have already added CORS policy in APIGEE. But still getting same issue when running from browser. From rest client its working fine. pl. sugggest


<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <AssignMessage async="false" continueOnError="false" enabled="true" name="Add-CORS"> <DisplayName>Add CORS</DisplayName> <FaultRules/> <Properties/> <Add> <Headers> <Header name="Access-Control-Allow-Origin">*</Header> <Header name="Access-Control-Allow-Credentials">true</Header> <Header name="Access-Control-Allow-Headers">Authorization,origin, x-requested-with, accept, content-type</Header> <Header name="Access-Control-Max-Age">3628800</Header> <Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header> </Headers> </Add> <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables> <AssignTo createNew="false" transport="http" type="response"/> </AssignMessage>

Hi @Chaitanya Bilaware, while making a call from browser open Browser Developer Tools >> Console and check the error.

Recently I was getting CORB Cross-Origin Read Blocking after adding CORS Policy in Apigee.

consoleerr.png

Error in console

Inspite of having CORS policy, Request header does not contain headers I pass . And the request is sent as OPTIONS not as POST.

@Siddharth Barahalikar- yes I am getting CORB error in firefox console. attaching it. How to solve this now?

imageerr2.png

sidd-harth
Participant V

Trying adding this resource with policies on ProxyEndpoint,

<Flow name="OptionsPreFlight">
            <Description/>
            <Request>
                <Step>
                    <Name>JavaScript-1</Name>
                </Step>
            </Request>
            <Response>
                <Step>
                    <Name>add-cors</Name>
                </Step>
            </Response>
            <Condition>request.verb = "OPTIONS"</Condition>
        </Flow>
 if (context.getVariable("request.header.Access-Control-Request-Headers.values.count") > 0)
	{
		var headersCollectionStr = context.getVariable("request.header.Access-Control-Request-Headers.values")+'';
		// comes back as "[header1, header2, header3]", so need to strip square brackets
		context.setVariable("reqHeaders", headersCollectionStr.substring(1, headersCollectionStr.length-1));
	}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="add-cors">
    <DisplayName>Add CORS</DisplayName>
    <FaultRules/>
    <Properties/>
    <Add>
        <Headers>
            <Header name="Access-Control-Allow-Origin">*</Header>
            <Header name="Access-Control-Allow-Headers">{reqHeaders}</Header>
            <Header name="Access-Control-Max-Age">3628800</Header>
            <Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>

@Siddharth Barahalikar I am getting erro on APIGEE portal ,when I am trying to add <FLOW> you mentioned.err3.png

My proxyendpoint xml is as follows


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ProxyEndpoint name="default">
    <Description/>
    <FaultRules/>
    <Flow name="OptionsPreFlight">
            <Description/>
            <Request>
                <Step>
                    <Name>JavaScript-1</Name>
                </Step>
            </Request>
            <Response>
                <Step>
                    <Name>Add-CORS</Name>
                </Step>
            </Response>
            <Condition>request.verb = "OPTIONS"</Condition>
        </Flow>
    <PreFlow name="PreFlow">
        <Request>
            <Step>
                <Name>Extract-Variables-1</Name>
            </Step>
            <Step>
                <Name>Java-Callout-1</Name>
            </Step>
        </Request>
    </PreFlow>
    <PostFlow name="PostFlow">
        <Request/>
        <Response>
            <Step>
                <Name>Add-CORS</Name>
            </Step>
        </Response>
    </PostFlow>


    <HTTPProxyConnection>
        <BasePath>/sample</BasePath>
        <Properties/>
        <VirtualHost>default</VirtualHost>
    </HTTPProxyConnection>
    <RouteRule name="noroute"/>
</ProxyEndpoint>

Original xml , before adding your solution

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ProxyEndpoint name="default">
    <Description/>
    <FaultRules/>
    <PreFlow name="PreFlow">
        <Request>
            <Step>
                <Name>Extract-Variables-1</Name>
            </Step>
            <Step>
                <Name>Java-Callout-1</Name>
            </Step>
        </Request>
        <Response>
            <Step>
                <Name>Add-CORS</Name>
            </Step>
        </Response>
    </PreFlow>
    <PostFlow name="PostFlow">
        <Request/>
        <Response/>
    </PostFlow>
    <Flows/>
    <HTTPProxyConnection>
        <BasePath>/sample</BasePath>
        <Properties/>
        <VirtualHost>default</VirtualHost>
    </HTTPProxyConnection>
    <RouteRule name="noroute"/>
</ProxyEndpoint>

The <Flow> tag should be inside <Flows> tag.

<Flows>

<Flow> </Flow>

</Flows>


Check this image -

http://prntscr.com/k8d70x