Express JS: No 'Access-Control-Allow-Origin' header is present on the requested resource

前端 未结 3 726
暗喜
暗喜 2020-12-09 00:02

I have an API running on a server and a front-end client connecting to it to retrieve data. I did some research on the cross domain problem and has it working. However I\'ve

相关标签:
3条回答
  • 2020-12-09 00:06

    You can also use cors npm for the same.

    **npm i cors**
    
    const cors = require('cors')
    
    var corsOptions = {
      origin: '*',
      optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 
    }
    app.use(cors(corsOptions));
    
    var routes = require('./api/routes/route'); //importing route
    routes(app); //register the route
    
    0 讨论(0)
  • 2020-12-09 00:09

    Instead of setting the request headers to your express route, Can you try setting it to express instance itself like this,

    var express = require('express');
    var app = express();
    var Assessment = require('../app/models/assessment');
    
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    
    app.post('/api/status', function (req, res, next) {
        // your code goes here
    });
    
    module.exports = app;
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-09 00:09

    Check your server.js file. It should look like the example below:

    const express = require('express');
    const bodyParser = require('body-parser');
    var cors = require('cors');
    const mongoose = require('mongoose');
    // create express app
    const app = express();
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: true }))
    
    // parse application/json
    app.use(bodyParser.json())
    
    app.use(cors());
    
    0 讨论(0)
提交回复
热议问题