As part of integrating the WebSphere
Commerce REST services in Angular2 application, created bunch of WCS MOCK REST
Services for unit testing using SOAP UI. It helps to test multiple scenarios
(different data and fail scenarios
...etc).
You can use SOAPUI or other tools
to mock the REST services during the development.
1.
Create and Start mock services (or you may
backend services running on different port)
While creating the MOCK Service, I
have given following port and host address.
Start the mock services by clicking
“run” button, then you can access mock services on http://localhost:4646
Problem : You will see
the problem similar to below when you try to access these MOCK services from
the Angular2 App because of cross domain (same origin) policy issues, We can
mitigate this by adding Cross-Origin-Resource-Sharing (CORS) headers in server level , if you
backend (api server) supports.
Error:
Cross-Origin Request Blocked: The Same Origin Policy
disallows reading the remote resource at
http://localhost:4646/wcs/resources/store/14321/cart/shipping_modes. (Reason:
CORS header ‘Access-Control-Allow-Origin’ missing).
Solution: As I am not using the any backend API server running
in my local for adding CORS headers, thought to use the angular2 proxy
configuration to bypass this errors.
1.
Create proxy.config.json file under project root
directory
2.
Add following in proxy configuration file
{
"/localapi/*": {
"target": "http://localhost:4646",
"pathRewrite": {
"^/localapi":
""
},
"changeOrigin": true,
"secure": false,
"logLevel":
"debug"
}
}
3.
Then start the local angular dev server as shown
below
a.
Using NPM START
Add “—proxy-config proxy.config.json” in package.json as shown below.
b.
Or Using NG SERVE
:/> ng serve
–proxy-config proxy.config.json
4.
Use the “/localapi” context while making HTTP
call from the angular 2
http.get("/localapi/wcs/resources/store/14321/cart/shipping_modes",
options)
5.
Now when you access the application then browser
makes call on 4200 port and get response from SOAP UI mock service that is
running on 4646.