问题
I've tried everything to get around the CORS error I am receiving. For oauth flow, to redirect your app to the Salesforce login screen (but this url auto redirects behind the scenes from salesforce to salesforce)
XMLHttpRequest cannot load salesforce url 2 Redirect from salesforce url 1 to salesforce oauth url 2 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I've installed CORS module and also tried this:
app.use('/public',function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
// Request headers you wish to allow
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-
With, Content-Type, Accept");
// Set to true if you need the website to include cookies in the
requests sent
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
Can anyone actually get this working and help?
回答1:
I just wrote a blog couple of days back: http://nodexperts.com/blog/salesforce-oauth-using-nodejs/
First of all, this will help you a lot in setting up OAuth2 and SalesForce in your Node-Express app.
Another thing is that you can go from your app -> SalesForce login app -> your_redirect_uri.
You will only get CORS error when you're doing this from server-to-server.
So, if you have an app which has some UI and some user interaction, then I would suggest you to redirect to SalesForce page from your client code.
Here's a snippet of how you can redirect to login page of Salesforce using express roure and jsforce npom package:
app.get('/oauth2/auth', function(req, res) {
const oauth2 = new jsforce.OAuth2({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET_ID,
redirectUri: `${req.protocol}://${req.get('host')}/${process.env.REDIRECT_URI}`
});
res.redirect(oauth2.getAuthorizationUrl({}));
});
And this is how you can set your SalesForce conncted app, redirect url:
app.get('/redirect_uri', function(req,res) {
const oauth2 = new jsforce.OAuth2({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET_ID,
redirectUri: `${req.protocol}://${req.get('host')}/${process.env.REDIRECT_URI}`
});
const conn = new jsforce.Connection({ oauth2 : oauth2 });
conn.authorize(req.query.code, function(err, userInfo) {
if (err) {
return console.error(err);
}
console.log(conn.accessToken);
});
});
Hope, everything is clear, let me know in case of any clarification.
来源:https://stackoverflow.com/questions/43150587/salesforce-oauth-redirect-cors-issue-node-express-app