0

I have a C# / ASP.NET Core Web API project running on https://localhost:7001 and a next js app running on http://localhost:3000.

I can run the C# API from swagger and directly in the browser (https://localhost:7001/api/SourceSystems), but when I try to call it from the next js page using GetStaticProps, I get a 500 error.

Next.js code:

export default function Sourcesystem({systems}) {
  return (
    <ul>
    {systems.map((system) => (
      <li key={system.systemName}>{system.systemName} </li>
    ))}
  </ul>
  )
};
// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch(
    'https://localhost:7001/api/Schedules',
    {
      method:'GET',
    }
  )
  const systems = await res.json()
  console.log(systems);
  return {
    props: {
      systems
    },
  }
}

I have added CORS to the c# code (I think) in program.cs

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins(
                              "http://example.com",
                              "http://www.contoso.com",
                              "http://localhost:3000"
                          );
                      });
});

// services.AddResponseCaching();
builder.Services.AddControllers();
// add dbContext
builder.Services.AddDbContext<GdqcDevContext>(options => options.UseSqlServer("Data Source = RAZERPRO17; Initial Catalog = GDQC_dev; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = False; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"));

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();

}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();

Next is saying the the fetch failed:

enter image description here

I am suspecting something still not set correctly for CORS but I have copied the CORS configuration and the middleware assignment order from documentation and other stackoverflow answers. NOTE: I am running the c# API code using the debug browser rather than directly from IIS. I have read somewhere about the OPTIONS but this is only for the full blown IIS

I have also added a CORS guard annotation to the c# controller with no success

namespace Overwatch_API.Controllers
{
    [EnableCors("MyAllowSpecificOrigins")]
    [Route("api/[controller]")]
    [ApiController]
    public class SourceSystemsController : ControllerBase
    {
        private readonly GdqcDevContext _context;

        public SourceSystemsController(GdqcDevContext context)
        {
            _context = context;
        }

        // GET: api/SourceSystems
        [HttpGet]
        public async Task<ActionResult<IEnumerable<SourceSystem>>> GetSourceSystems()
...

UPDATE: It looks like Next is returning the following error message in the logging:

cause: Error: self-signed certificate
      at TLSSocket.onConnectSecure (node:_tls_wrap:1538:34)
      at TLSSocket.emit (node:events:513:28)
      at TLSSocket._finishInit (node:_tls_wrap:952:8)
      at ssl.onhandshakedone (node:_tls_wrap:733:12) {
    code: 'DEPTH_ZERO_SELF_SIGNED_CERT'

I presume this is related to the SSL cert on the .net core 6 api code, as this is being called with https. How do I get next to accept a self signed cert, or build a propertly signed cert for the dev environment

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Aaron Reese
  • 544
  • 6
  • 18
  • If it was a CORS error, you would be getting an error specific to CORS, not a 500 error. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors A 500 error is an internal server error. You can try setting Mode, Credentials, Method, etc. to make sure they work with your API. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – computercarguy Jan 04 '23 at 21:54

1 Answers1

0

This issue is common in nextjs.

I found two ways to fixed it.

1. If the issue occurs in dev environment. we can use NODE_TLS_REJECT_UNAUTHORIZED=0 to solve it.

Overcome the DEPTH_ZERO_SELF_SIGNED_CERT on Node.js

Self Signed SSL Certificate in NextJS

2. We also can use NODE_EXTRA_CA_CERTS to solve it. It can be used in Dev or Prod Environment.

Node TLS socket : DEPTH_ZERO_SELF_SIGNED_CERT error

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • Hi @AaronReese, could you share the strcture of the nextjs project ? Pls hide your sensitive information. – Jason Pan Jan 06 '23 at 12:35
  • Hi Jason. Newly created Next 12 app using Create-Next-App so completely standard strucuture. I have added one file to the pages directory which has the code in the above snippets. – Aaron Reese Jan 06 '23 at 12:38
  • Thanks for the links Jason. I am not sure which files they are referring to in the posts though. Where do I find the node start file (1st link) or NexJS dev scipt (2nd link). I tried making the change to my package.json scripts section but now I get an error message "'NODE_TLS_REJECT_UNAUTHORIZED' is not recognized as an internal or external command," when I npm run dev. – Aaron Reese Jan 06 '23 at 12:40
  • for reference I am on Windows 11 – Aaron Reese Jan 06 '23 at 12:43
  • @AaronReese Try this https://github.com/sitevision/sitevision-apps/issues/6#issuecomment-645842552 – Jason Pan Jan 06 '23 at 12:46
  • @AaronReese Try to use cross-env. – Jason Pan Jan 06 '23 at 12:49
  • sorry Jason I'm lost now. I know you are not my personal support desk, but the whole point of trying to use next is that it should just be plug and play. I can't believe how many hoops there are to jump through just to get two instances of webservers talking to each other on the same development machine.; this feels like a major failing of node;having to edit packages downloaded by npm and install additional dependencies. I'm happy to bin the current next project and start again if you can provide me with an idiots guide... – Aaron Reese Jan 06 '23 at 12:57
  • @AaronReese I will follow the nextjs doc and try it in my local, will update next week. – Jason Pan Jan 06 '23 at 13:01