I get the error "cross origin request blocked" even tough i have the express cors package

35 views Asked by At

My App code:

import express, {Express, Request, Response, Router} from 'express';
import dotenv from 'dotenv';
import ArtistRouter from './routes/artist_routes';
import infoRouter from './routes/info_router';
import bodyParser from 'body-parser';
//Autor: Yannick Hiltscher 

dotenv.config();
const cors = require('cors');
const app: Express = express();
app.use(cors());
var BodyParser=require('body-parser')

app.use(ArtistRouter);
app.use(infoRouter);
app.use(bodyParser.json())

const port = process.env.PORT;
app.listen(port, () => {
    console.log(`Server started at http://localhost:${port}`);
});

my Router:

ArtistRouter.post('/artist', async (request,response) => {
    var Nation = request.body.Nation;
    var GB = request.body.GB; 
    var FN= request.body.FN;
    var LN=request.body.LN;
    var Web=request.body.Website;
    var Insta=request.body.Insta;
    var Rating=request.body.Rating;
    NewArtists(request, response, Nation, GB, FN, LN, Web, Insta, Rating);



My Next js code:

   const ArtistData = {
      "Nation":"Australia",
      "GB":"amogus",
      "FN":"ei9fj",
      "LN":"eifj",
      "Website":"woi",
      "Insta":"fij",
      "Rating":"fjfj",
    }

    const API='http://localhost:8081/artist'
    axios.post(API, ArtistData)
        .then(response => {
           console.log('New artist created:');
           displaySuccessMessage("Artist created");
       })
        .catch(error => {
           console.log(ArtistData)
            console.error('Error creating artist:', error);
            displaySuccessMessage('Error creating artist');
       });
          const A=1;
         return A;
       }

I want my next js Program to give a few Variables to my API, but i get the Error "Cross origin request blocked"

Sadly, i cannot get it to work and i dont know why. Does anyone have an Idea why my Nextjs server doesnt have the permission for the post request?

1

There are 1 answers

0
Saranraj S On

Try this

import express from 'express';
import dotenv from 'dotenv';
import ArtistRouter from './routes/artist_routes';
import infoRouter from './routes/info_router';
import bodyParser from 'body-parser';
//Autor: Yannick Hiltscher 
import cors from 'cors'
dotenv.config();
const app = express();
app.use(bodyParser.json())
app.use(cors());
app.use(ArtistRouter);
app.use(infoRouter);
const port = process.env.PORT || 8081;
app.listen(port, () => {
    console.log(`Server started at http://localhost:${port}`);
});