How to proxy my API URL to some other proxy - reactjs

I am on http://localhost:8081/post URL and my API is hosted at some "http://dummy.restapiexample.com/api/v1".
I want it to appear in the network tab like "/custom/create". But the network tab is showing "http://localhost:8081/custom/create" but it should not append localhost URL in that. It should take the hosted API URL.
I am using CRA boilerplate. And I do not want to use express for the same.
I tried the following code
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/custom",
{target: "http://dummy.restapiexample.com/api/v1"}));
};
and in for API calls, I am using below format:
fetch('/custom/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(authData),
})
I am not getting how to hide the whole Hosted API URL and show proxy URL
in the network tab.
Please give your valuable suggestion over this.
I am a novice in proxy-middleware. Thank you in advance :)

In your package.json include the url of your API as a proxy.
"proxy": "http://dummy.restapiexample.com",

Related

React Client Cors issue

I am learning react, I currently have a .net core API running in visual studio on localhost:7071.
The Local API is not running cors as there is no requirement for it to use Cors.
Creating a simple react client using the following will not return data due to a cors error?
I have tried a number of solutions online and none of them work, so how can I make this "simple" react client work without generating the following error
Access to XMLHttpRequest at 'http://localhost:7071/api/Users' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
function GetApiResults(){
const axios = require('axios').default;
axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*";
axios({
method: 'get',
headers: { 'Content-Type': 'application/json' },
url: 'http://localhost:7071/api/Users',
}).then(function (response) {
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
export default GetResults;
You have a pretty straighforward description of the issue, browser expects the external resouces you are using (API in your case, external in terms it is not on same port) to provide CORS headers. If they are not set - browser will not execute the request. It will execute the request if you open the resource URL in browser tab, but if you are on localhost:3000 - any requests initiated by this page to anything that is not on localhost:3000 will require CORS to be set.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called the same-origin policy. The same-origin policy prevents a malicious site from reading sensitive data from another site.
So either enable CORS support in your backend, either use CRA feature called Proxy: https://create-react-app.dev/docs/proxying-api-requests-in-development/
I prefer the manual proxy configuration, at the very end of the article.
Important: this proxy is for DEVELOPMENT only!
Here is a step-by-step instruction, just tested:
Install npm install http-proxy-middleware --save
Add src/setupProxy.js with content:
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/api",
createProxyMiddleware({
// I have a different port and Visual Studio might randomly change it
// Fix: edit running configuration
// https://stackoverflow.com/questions/70332897/how-to-change-default-port-no-of-my-net-core-6-api
// Notice: no /api at the end of URL, it will be added.
// more details at: https://www.npmjs.com/package/http-proxy-middleware
target: "https://localhost:7002",
changeOrigin: true,
// Im using .net core 6 starting api template
// which is running with a self-signed ssl cert with https enabled
secure: false
})
);
};
Modify your AXIOS configuration object to use new URL:
function GetApiResults() {
const axios = require("axios").default;
axios({
method: "get",
headers: { "Content-Type": "application/json" },
url: "/api/WeatherForecast"
})
/* ... */
}
Note: Im using default web api project, only changed [Route("api/[controller]")] (added api/) for Controller.
Restart the app and watch for logs from npm start output, proxy can log some errors there.
CORS is a browser feature. So, the browser you are using to access the React app must require you to use CORS. You need to setup CORS on your backend and allow connections from remote origin.
It will be good if you add CORS enabling code on Server Side. if your server-side app is in Express JS then add below middleware-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Origin", "http://localhost:3000"); or add your react app url.
next();
});

React + Atlassian Jira Cloud Api + Cors Anywhere: Adding a worklog via POST returns 403

Been stuck on this for a few days now. I'm making an app in React that uses Atlassian's Jira Cloud Rest API and I want to log work on a Jira issue from my app. However every time I try I get a 403. The same request in Postman works, it creates the worklog, which is weird. I set up a certificate and use cors-anywhere to be able to use HTTPS in my React app, but otherwise the query is the same.
I've read a bunch of entries on Atlassian's forums about people being unsure about what to do when they need to POST to an Atlassian API. Is this something bizarre that can't be fixed, or am I missing a relevant header?
Here is the fetch call I make in my React app's ComponentDidMount(). https://localhost:8080 is the proxy I use for CORS-anywhere/Yarn.
fetch("https://localhost:8080/my-domain.atlassian.net/rest/api/2/issue/ISSUE-1/worklog,{
headers: {
"Access-Control-Allow-Origin": "https://localhost:3000/",
"X-Atlassian-Token": "no-check",
"Content-Type": "application/json;charset=UTF-8",
"Authorization": "Basic base64token",
},
method: "POST",
responseType: 'json',
body: {
"timeSpent":"2h 48m",
"author":{
"accountId":"123456789",
"active":true,
"avatarUrls":{
"16x16":"https://avatar-cdn.atlassian.com/...",
"24x24":"https://avatar-cdn.atlassian.com/...",
"32x32":"https://avatar-cdn.atlassian.com/...",
"48x48":"https://avatar-cdn.atlassian.com/..."
},
"displayName":"User Name",
"emailAddress":"user.name#gmail.com",
"key":"user.name",
"name":"user.name",
"self":"https://my-domain.atlassian.net/rest/api/2/user?username=user.name",
"timeZone":"Europe/Stockholm"
},
"comment":"bla bla bla",
"started":"2018-07-19T21:32:18.843+0200"
}
})
.then((res) => res.json())
.then(function(resJson){
console.log(resJson
})
And this is my server.js that Yarn runs.
const path = require('path')
const fs = require('fs')
const express = require('express')
const https = require('https')
const app = express();
const host = process.env.HOST || '0.0.0.0';
const port = process.env.PORT || 8080;
const cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
httpsOptions: {
key: fs.readFileSync(path.resolve('server.key')),
cert: fs.readFileSync(path.resolve('server.crt'))
},
originWhitelist: ['https://localhost:3000', 'https://localhost:8080'],
requireHeader: ['origin', 'x-requested-with'],
removeHeaders: ['cookie', 'cookie2']
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});
Instead of using basic auth you should consider building an atlassian connect add-on. You could use atlassian-connect-express to start with, it will handle installation of the add-on and validation of JWT tokens. Basically, you will be able to do secure calls from your server (signed with JWT tokens) or do calls to Jira API from your front-end (embedded inside Jira) that will be executed as a particular user, which will generate proper "updated by" entries.

Axios having CORS issue

I added proxy in package.json and it worked great, but after npm run build the CORS issue has resurfaced again, does anyone know how to deal with CORS issue after npm run build in React.
I have tried to add headers in axios request using various methods. However, I failed to add 'Access-Control-Allow-Origin':'*' in axios request. My code is as follwing:
package.json
"proxy": {
"*":{ "target" : "http://myurl"}
}
GetData.js
axios.defaults.baseURL = 'http://myurl';
axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.get(serviceUrl, onSuccess, onFailure)
.then(resp => {
let result = resp.data;
onSuccess(result);
})
.catch(error => {
if(onFailure) {
return onFailure(error);
}
})
}
Note: It has enabled from server side, it is still not working.Currently, I can't change code from server side, My work is limited to client side only.
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
Just noting my solution for someone who might get here from googling. I resolved my CORS issue (when calling an external api from my UI in the browser) by setting withCredentials to false in my axios call:
axios({
method: 'get',
url: `https://api.someurl.com/subject/v2/resource/somevalue`,
withCredentials: false,
params: {
access_token: SECRET_TOKEN,
},
});
In this case, the external api's endpoint's security is based on the access_token.
May be helpful to someone:
I'm sending data from a react application to a golang server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"), the error was fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
I have encountered with same issue. When I changed content type it has solved. I'm not sure
this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources. So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.
Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.
const cors = require("cors");
app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));
app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));
I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.
I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.
You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security
After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.
Hope this helps!
This work out for me :
in javascript :
Axios({
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order
}).then(function (response) {
console.log(response.data);
});
and in the backend (.net core) :
in startup:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
and in controller before action
[EnableCors("AllowOrigin")]
CORS issue is something you will only encounter on a Broswer. It occurs beacuse the server does not allow request from others servers
i.e If I am sending request from http://localhost:3000 to any api(http://example.com/users) to get the user data from here.
If the server does not recognize your local host
#CrossOrigin(Origin = "*") // this will allow any request from any server you will not face CORS issue if you us this annotation
Now what if you are sending a request using axios in react to another sever which is not in your control the way to overcome that issue is by using http-proxy-middleware
npm i http-proxy-middleware // install this dependency
axios.{
method: 'post',
url: '/endpoint',
headers: {
'Content-Type': 'application/json',
},
proxy: createProxyMiddleware({
target: 'https://www.api.com',
changeOrigin: true}),
data: data
};
Now in this way a proxy request to www.api.com/endpoint will be sent and thus you will not recieve a cors issue
also add this in your package.json
"proxy": "https://www.api.com"
I come across this thread when having the same problem using Axios. What was not mentioned in the responses is that using fetch with no-cors mode can solve your issue.
Why ?
Apparently, Axios uses a XMLHttpRequest under the hood, not Request
and Axios fails because CORS is still being enforced and no-cors mode
is not supported.
Check this thread for more information
Please try this .. it worked for me
axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
console.log("result",result);
}).catch((error)=>{
console.log("Error",error);
});
Just simply add this to your headers
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
No need to use Access-Control-Allow-Origin : *
CORS issue can be simply resolved by following this:
Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

http post request in reactjs not working

I am trying to make a http post request from my reactjs application to express that locally hosted as well. I dont need to pass anything from this post request (no params needed), i just want the request to go through. All params have been specified in my express code. I am running my reactjs application locally in a different port. Here is how i am doing it.
fetch('http://localhost:8080/api/send', { 'mode': 'no-cors' }, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: {
}
});
This link works on the postman, just this http post method isn't working. Any help would be appreciated.
For me, it is working when I remove ,
{ 'mode': 'no-cors' }
Also, assuming you're body: has content (it's empty right now so therefore wouldnt do anything on a POST request): you should add JSON.stringify() to the body. So:
body: JSON.stringify({
//content here
})
If cors is giving you issues, there's an easy way to fix that on the back end (specifically with rails).

Angular Token based Auth with CORS

I'm trying to create a cross domain request with angular 1.4.7. I'm pretty new to this topic and especially in this scenario I'm not able to find any help via google.
Environment:
I try to call from the angular app A served by www.a.com the restful api's offered by the server B served by www.b.com.
The thing im struggling over is, that I have to authorise myself a via token in the http post. This token constelation should look like:
{
"account": {
"hashcode": "somehashcode"
},
"hashkey": "somehashkey"
};
I tested the api with Postman an it works well, but I'm failing to realise it with angular.
postman successful try picture 1
postman successful try picture 2
To enable cors in my app.js:
.config(['$httpProvider', function($httpProvider){
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
}]);
An my request:
$http({
url: 'http://evori-api.azurewebsites.net/api/handshake',
method: 'POST',
data: authtoken,
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data, status) {
console.log(data + status);
}, function() {
});
Any help would be appreciated. Even if you just got an article or blog that explains how such things should be done. I know there is probably just a dumb mistake or something but it drives me crazy.
Thanks a lot.
It seems like the problem wasn't me or my api call. The source of the problem was, that the server didn't handle the OPTION call that leads each cors request.

Resources