Created
February 16, 2021 06:16
-
-
Save Vijaysinh/c2a70a46078beda8ec24693d3e1d7975 to your computer and use it in GitHub Desktop.
Node JS CORS Enable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
var fs = require("fs"); | |
const bodyParser = require("body-parser"); | |
/** bodyParser.urlencoded(options) | |
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST) | |
* and exposes the resulting object (containing the keys and values) on req.body | |
*/ | |
app.use(bodyParser.urlencoded({ | |
extended: true | |
})); | |
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.get('/listUsers', function (req, res) { | |
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { | |
console.log( data ); | |
res.end( data ); | |
}); | |
}) | |
app.post('/addUser', function (req, res) { | |
console.log(req.body.name); | |
try { | |
const data = fs.appendFileSync('user.txt',JSON.stringify(req.body)) | |
} catch (err) { | |
console.error(err) | |
} | |
}) | |
var server = app.listen(8081, function () { | |
var host = server.address().address | |
var port = server.address().port | |
console.log("Example app listening at http://%s:%s", host, port) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
$.ajax({ | |
headers: { "Accept": "application/json"}, | |
type: 'POST', | |
url: 'http://127.0.0.1:8081/addUser', | |
crossDomain: true, | |
data:{"email":profile.getEmail()}, | |
beforeSend: function(xhr){ | |
xhr.withCredentials = true; | |
}, | |
success: function(data, textStatus, request){ | |
console.log(data); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment