I am developing a web application with react. To call the API's I am using HTTP triggers in Azure function apps. All the API's are working without an issue. I am in the integrating process. I came across this CORS issue. I have tried to overcome this but I am still getting the same error. and I dont have an express.js
Program.cs
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
policy =>
{
policy.WithOrigins("http://localhost:3000");
});
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<EmployeeDBContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("EmployeeDB")));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
ReactApp
const makeAPICall = async () => {
try {
const response = await fetch('http://localhost:7182/api/GetEmployees', {mode:'cors'});
const data = await response.json();
console.log({ data })
}
catch (e) {
console.log(e)
}
}
useEffect(() => {
makeAPICall();
}, [])
return (
<div className="App">
<h1>React Cors Guide</h1>
</div>
);
}
Updated
I found out that the problem is Missing Header.
Middlewares like this have to be places in the pipeline in correct order and sometimes other middlewares have to be enabled
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-7.0#middleware-order
According to your issue, it seems that app.UseRouting() is missing (may be something else, article above definitely knows it better)
Related
I setup sentry cloud in our React application but its blocked by AdBlockers (when turning Adblocker off, it works).
Is there someone who successfully setup a tunnel in a react application?
I played around with CORS but it didn´t work
Playing around with the tunnel property in Sentry.init from the nextjs example in https://github.com/getsentry/examples/blob/master/tunneling/nextjs/pages/api/tunnel.js is throwing a /tunnel 404 (Not Found) console error in react app although I added a route to this path into my App which contains the handle function from nextjs example.
...
Sentry.init({
dsn: 'https://mine#mine.ingest.sentry.io/mine',
integrations: [new BrowserTracing()],
environment,
tunnel: '/tunnel',
tracesSampleRate,
});
...
where I tried it directly via <Route path='/tunnel' component={(req, res) => handle(req, res)} /> and also by using a component <Route path='/tunnel' component={Tunnel} /> with
function Tunnel(props) {
let location = useLocation();
useEffect(() => {
if(location.pathname === '/tunnel') {
handle(props.req, props.res);
}
}, [location.pathname]);
return null;
}
I even tried Webpack Plugin
plugins: [
new SentryWebpackPlugin({
include: '.',
ignore: ['node_modules'],
org: 'my_org',
project: 'app',
authToken:
'myToken',
}),
],
but it also is being getting blocked
--- Update ---
At least for local development and testing its possible to adjust the webpack config.
const bodyParser = require('body-parser')
const sentryHost = '#o<orgId>.ingest.sentry.io';
// Set knownProjectIds to an array with your Sentry project IDs which you
// want to accept through this proxy.
const knownProjectIds = ['12345'];
app.use(bodyParser.text());
app?.post('/tunnel', async (req, res) => {
try {
const envelope = req.body;
const pieces = envelope.split('\n');
const header = JSON.parse(pieces[0]);
// DSNs are of the form `https://<key>#o<orgId>.ingest.sentry.io/<projectId>`
const { host, pathname } = new URL(header.dsn);
// Remove leading slash
const projectId = pathname.substring(1);
if (host !== sentryHost) {
throw new Error(`invalid host: ${host}`);
}
if (!knownProjectIds.includes(projectId)) {
throw new Error(`invalid project id: $. {projectId}`);
}
const sentryIngestURL = `https://${sentryHost}/api/${projectId}/envelope/`;
const sentryResponse = await fetch(sentryIngestURL, {
method: 'POST',
body: envelope,
});
sentryResponse.headers.forEach(([key, value]) => res.setHeader(key, value));
res.status(sentryResponse.status).send(sentryResponse.body);
} catch (e) {
captureException(e);
return res.status(400).json({ status: 'invalid request' });
}
res.send("POST res sent from webpack dev server")
})
but only for local testing. In production I guess we would use a proxy.
Hey I think the problem in my code is on the frontend react cod because if I use Postmap my api on nest works correct.
What I have to do: I'm checking on the backend if the input phare is correct. If yes it will answers to the post request sending an object contained urls of images than I will render.
In my console log when I try to post the request I have the attached image error:
This is my function that handle the request:
const getImages = async (secret) => {
try {
const response = await axios.post('http://localhost:5000/secret', {secret});
return response.data;
} catch (error) {
console.log(error);
}
}
const handleSecret = async (e) => {
secret = phrase;
console.log(secret)
if (e.key === "Enter" || e.type === "click") {
const images = await getImages(secret);
if (images) {
//render image if true
setSecret(true);
} else {
window.alert("Incorrect phrase");
setSecret(false);
}
}
}
I need community help!
I have already enable cors on nest backend:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(5000);
app.enableCors();
}
bootstrap();
You need to enable cors before using app.listen(). Think of regular express middleware, anything after app.listen() doesn't get bound to the server, it's the same thing here
I have an ASP.NET Core 6 Web API for Windows authentication which is like this:
[HttpGet("GetIdentity")]
public IActionResult GetIdentity()
{
var userName = HttpContext.User.Identity.Name;
return Ok(new { UserName = userName });
}
and everything works fine. Then I called this API from reactjs like this:
import React, { useEffect, useState } from "react";
function UserNameApi() {
const [users, setUser] = useState("");
const fetchData = () => {
return fetch("http://localhost:8000/User/GetIdentity",{withCredentials:true})
.then((res) => {res.json()
.then((result) => setUser(result.userName));
});
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
<p>UserName:{users}</p>
</div>
);
}
export default UserNameApi;
I published both server and client side on IIS but as I open the page, I get an http 401 unauthorized error. I can call the API in the browser, and also used postman and by setting NTLM it works too. I have to add that I have set CORS in API and IIS too.
I will appreciate it if anyone can help me.
Thanks in advance
UPDATE
After adding below code and facing CORS issue.
Change AddCors code like below can fix it.
// Add services to the container.
builder.Services.AddCors(options =>
options.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyMethod()
.SetIsOriginAllowed(_ => true)
.AllowAnyHeader()
.AllowCredentials();
}));
...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseAuthorization();
...
In addition to setting "withCredentials" to "true", you should also set "credentials" to "include". This should allow the browser to send the Windows credentials to the server.
Code should like below:
const fetchData = () => {
return fetch("http://localhost:8000/User/GetIdentity",{
withCredentials: true,
credentials: "include"
})
.then((res) => {
res.json()
.then((result) => setUser(result.userName));
});
};
When I request data from Mongoose, it shows me an error and tells me that the page does not exist, knowing that I tested the back-end in Postman and it succeeded. I also tested the react by fetching data from an external link and it succeeded. I do not know what the problem is?!
I try with this code
This is my back-end code
const app = require("./app");
const mongoose = require("mongoose");
app.set("port", process.env.PORT || 3000);
const mongoURI = "mongodb://localhost:27017/get-now";
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log(`database connected`))
.catch(err => console.log(err));
const port = process.env.PORT || 3000;
app.listen(port, () => {console.log(`the server is ${port}`)});
routes.get("/alldata" , async (req, res) => {
try {
const foodDatas = await Data.find({})
res.send(foodDatas);
console.log(foodDatas)
} catch (error){
res.status(500).json({
Error: error
})
}
});
This is my front-end (Reactjs) code
const fetchData = async () => {
axios.get('http://localhost:3000/alldata')
.then((res) => {
console.log(res.data)
}).catch (err => {
console.log(err)
})
}
useEffect(() => {
fetchData()
}, [])
All these don't work it give me Error 404 page with data: undefined
did you configure the cors in the app file?
if don't, please install cors.
and add:
const cors = require('cors')
also:
app.use(
cors({
origin: "*",
})
);
Note:
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources
I'm using a service to access user's geolocation.
The problem is that the request works ONLY when I turn on the "Network inspection" mode in the react-native debugger.
Otherwise it fails with an error:
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
at XMLHttpRequest.js:507
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:366)
at MessageQueue.js:106
at MessageQueue.__guard (MessageQueue.js:314)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)
For data fetching I'm using a regular fetch, but already tried XHR and axios with the same results.
export function getUserGeoLocation() {
const url = 'https://geoip.tradesmarter.com/json';
return fetch(url)
.then(response => response.json())
.catch(error => {
console.log(error);
});
}
The same request works on a web platform that's using Angular with jsonp.
export function getUserGeoLocation() {
const url = 'https://geoip.tradesmarter.com/json';
const opt = {
timeout: 1000,
};
const promise = new Promise((resolve, reject) =>
jsonp(url, opt, (err, data) => {
if (err) {
reject(err.message);
} else {
resolve(data);
}
})
);
return promise;
}
Has anyone ever encountered a problem like this one?
Have you added network ie Internet permission for android and ios