javascript - Setting Access-Control-Allow-Origin doesn't work with AJAX/Node.js -


i keep facing same error on , on again:

xmlhttprequest cannot load http://localhost:3000/form. no 'access-control-allow-origin' header present on requested resource. origin 'http://localhost:8000' therefore not allowed access. response had http status code 404. 

i've read countless posts similar 1 , pretty have same answer, namely add following setting: res.setheader('access-control-allow-origin', '*'). that's i've been doing still doesn't work. gave angular.js app on localhost:8000 (when btn clicked logsth() called) , node works on localhost:3000. here's like:

app.controller('contact', ['$scope', function($scope) {     $scope.logsth = function(){         var datas = {'may':'4','june':'17'};         $.ajax({           url: 'http://localhost:3000/form',           method: 'post',           crossdomain: true,           data: datas         });     }; }]); 

and node:

var express = require('express'); var router = express.router(); var app = express();  app.use(function (req, res, next) {     res.setheader('access-control-allow-origin', '*');     res.setheader('access-control-allow-methods', 'get, post, options, put, patch, delete');     res.setheader('access-control-allow-headers', 'content-type');     res.setheader('access-control-allow-credentials', true);     next(); });  app.post('/form', function(req, res){     console.log("e-mail sent");     res.send('yey'); });  module.exports = router; 

not code here i'm looking rid of error.

edit: when use app.use(...) , app.post(...) , go localhost:3000/form 404 error. when use router.use(...) , router.post(...) @ least link works fine. also, there no 'allow-origin' error, get: post http://localhost:3000/form 404 (not found). however, when go http://localhost:3000/form displays response , console.log. should leave router instead of app?

just leave single line did trick me:

res.setheader('access-control-allow-origin', '*'); 

update:

you can try install cors module from npm.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -