Home > Back-end >  How to use cors in node
How to use cors in node

Time:06-25

'use strict';

const app          = require('koa')();
const jwt          = require('koa-jwt');
const bodyParser   = require('koa-bodyparser');
const send         = require('koa-send');
const serve        = require('koa-static');
const jsonwebtoken = require('jsonwebtoken');
const error        = require('./middleware/error-middleware.js');
const router       = require('koa-router')();

// do not use this secret for production
const secret = 'supersecret';

app.use(error());
app.use(bodyParser());
app.use(serve('dist'));
app.use(jwt({ secret }).unless({
    path: [/^(?!\/api\/)/]
}));

// for example use, we just check for specific username/password
// in the real world, we would check a database and check hashed password
router.post('/auth', function* () {
    const username = this.request.body.username;
    const password = this.request.body.password;

    if (username !== 'chuck' && password !== 'norris') {
        this.throw(401, 'Invalid username/password.');
    }

    const user = {
        username,
        email: '[email protected]',
        firstName: 'Chuck',
        lastName: 'Norris',
        roles: ['admin']
    };

    const token = jsonwebtoken.sign(user, secret, {
        issuer: 'localhost',
        audience: 'someaudience',
        expiresIn: '1d'
    });

    this.body = { token };
});

app.use(router.routes());

app.use(function* () {
    yield send(this, '/dist/index.html');
});

app.on('error', err => console.log(err));

app.listen(3000, () => console.log('example running on port 3000'))

; //how to solve this error if I run a server with the port 80, and I try to use XMLHttpRequest I am getting this error: Error: listen EADDRINUSE Why is it problem for NodeJS, if I want to do a request, while I run a server on the port 80? For the webbrowsers it is not a problem: I can surf on the internet, ...

CodePudding user response:

Your problem has nothing to do with CORS.

You are trying to create a server that listens for incoming requests on port 80. (The code you’ve provided says port 3000, but I’ll assume you are asking about what happens when you change that).

The error message says you can’t run a server that is listening on that port, because it is in use. This means that you already have a server (possibly another instance of the same server, but more likely a different one such as Apache HTTP) already running and using port 80.

You can’t have two servers listening on the same port. If a browser make an HTTP request to port 80, then the computer wouldn’t know which of the two servers the request was intended for.

It is not a problem for web browsers because they do not listen for incoming requests. They make outgoing requests.

CodePudding user response:

//dal
const product = require('./Connection').db('store1').collection('productaa');

//object id access to the document based on the _id
const ObjectId = require('mongodb').ObjectId;


//create

const create = async ({name, price, description})=>{

    const result  = await product.insertOne({name , price,description});
    return result.ops[0];

}

//read all 

const GetAllProduct = async () =>{

    const pro = await product.find();
    return pro.toArray();

}

//read product by id 

const getProductByID = async(id)=>{

    return await product.findOne({_id:ObjectId(id)});
}


//update

const editProduct = async (id, {name ,price, description})=>{

    console.log(id);

    const result  = await product.replaceOne({_id:ObjectId(id)},
    {name , price, description});
    return result.ops[0];
    

}

//remove product

const removeByID = async id =>{
    await product.deleteOne({_id:ObjectId(id)});
}

module.exports = {removeByID,editProduct,getProductByID,GetAllProduct,create}




//api

//import  methods in dal 
const  {removeByID,editProduct,getProductByID,GetAllProduct,create} = require("../dal/Products.dao")


//map create method

const createProduct = async({name , description, price})=>{

    //create object
    const product ={
        name , 
        description, 
        price

    }
    return await create(product);
}


//get all methods 
const GetAll = async ()=>{

    return await GetAllProduct();
}


//get by id

const getProductID = async id=>{

    return await getProductByID(id);
}


//delete product
const removeProductID = async id =>{
    
return await removeByID(id);
}

//update 
const UpdateProduct = async(id,{name , description, price})=>{

    return await editProduct(id,{name , description, price});
}


//export to routes
module.exports={
    removeProductID, 
    UpdateProduct,
    GetAll,
    createProduct,
    getProductID

}

//routes const Router = require("@koa/router");

const { removeProductID,UpdateProduct, GetAll, createProduct, getProductID} = require ("../api/Product.api");

//define perfix const router = new Router({ prefix:'/products' }) //get all products

router.get('/all', async ctx=>{

ctx.body = await GetAll();

})

//add product

router.post('/add', async ctx=>{

let product = ctx.request.body;
product = await createProduct(product);

ctx.response.status = 200;
ctx.body = product;

})

//get item by id router.get('/:id' , async ctx=>{

const id =  ctx.params.id;
ctx.body = await getProductID(id);

} )

//delete product router.delete('/:id' , async ctx=>{

const id = ctx.params.id;
await removeProductID(id);
ctx.response.status = 200;

})

//update

router.put('/:id' , async ctx=>{

const id = ctx.params.id;
let product = ctx.request.body;

product = await UpdateProduct(id,product);
ctx.response.status = 200;
ctx.body = product;

})

module.exports = router;

CodePudding user response:

const  Koa = require('koa');

const bodyParser = require('koa-bodyParser');
const cors = require('@koa/cors');



const productRoutes = require('./routes/ProductRoutes');

const app = new Koa();

app.use(cors({
    origin: "http://localhost:1234",
    
}
  
));

   
app.use(bodyParser());


app.use(productRoutes.routes()).use(productRoutes.allowedMethods());



  
    //setup connection 
    
    app.listen(3000);
    console.log("application is running on port 3000")

//connect
const {MongoClient} = require("mongodb");

const client = new MongoClient('mongodb://localhost:27017', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

client.connect(err => {
    if(err){
        console.error(err);
        process.exit(-1);
    }
    console.log("Successfully connected to mongo");
})

module.exports = client;
  • Related