Front End-"learning experience"-cross-domain issues

Source: Internet
Author: User

We know that when you do the Web, you encounter so-called cross-domain issues.

The so-called cross-domain is the browser at the global level prohibits the page from loading or executing any script from a domain different from its source.

For example, our locally developed static interface writes AJAX requests that cannot be configured without a server response.

Of course, we can put the static interface under the server, such as Tomcat WebApp, or put in the Node Express project static path can be accessed successfully, of course, if you want to reduce the burden of the server, you can use the static file with Nginx proxy.

However, no matter how the development is more inconvenient, here to share with you how to make cross-domain.

We do not apply JSONP here because the request data is limited.

Using cors, prepare angular JS as the service side, express as the service side.

Directly on the code, first on the service side:

var express = require (' Express '); var path = require (' path '); var favicon = require (' Serve-favicon '); var logger = require (' Morgan '); var cookieparser = require (' Cookie-parser '); var bodyparser = require (' Body-parser '); var routes = require ('./web_router '); var app = Express ();
View engine Setup app.set (' Views ', Path.join (__dirname, ' views ')); App.set (' View engine ', ' Jade ');
 uncomment after placing your favicon in /public//app.use (Favicon (__ dirname +  '/public/favicon.ico ')); App.use (Logger (' dev ')); App.use (Bodyparser ()); App.use (bodyparser.urlencoded ({    extended: false})); App.use (Cookieparser ()); App.use (Express.static (Path.join (__dirname,  ' public '))); App.all ('/fruitpoint ',  function (req, res, next)  {    res.header (" Access-control-allow-origin ", " * ");     res.header ("Access-control-allow-headers",  "Content-type, content-length,  authorization, accept, x-requested-with ");     res.header ("Access-control-allow-methods",  "put,post,get,delete,options");     res.header ("x-powered-by",  ' 3.2.1 ')     if  (Req.method  ==  "OPTIONS")  res.send (200);     else next (); }); App.use ('/fruitpoint ',  routes);  catch 404 and forward to error handler app.use (function (Req, res,  next)  {    var err = new error (' Not Found ');      err.status = 404;     next (ERR); });  error handlers// development error handler// will print stacktrace if  (App.get (' env ')  ===  ' development ')  {    app.use (function (err,  Req, res, next)  {        res.status (err.status | |  500);         res.render (' Error ',  {             message: err.message,              error: err         });    &nBSP;}); }
Production error handler//No stacktraces leaked to user app.use (function (err, req, res, next) {Res.status (err.st ATUs | |     500); Res.render (' error ', {message:err.message, error: {}}); });
App.listen (3000); Console.log ("server start") Module.exports = app;

First show the app.js of Express, this gives a routing fruitpoint to increase the cross-domain setting before the request is executed by using Express to intercept multiple requests and release them before adding one.

Set response support for cross-domain code

   res.header ("Access-control-allow-origin", "*");    res.header ("Access-control-allow-headers", "Content-type, Content-length, Authorization, Accept,      x-requested-with ");    res.header ("Access-control-allow-methods", "put,post,get,delete,options");    res.header ("x-powered-by", ' 3.2.1 ')    if (Req.method = = "Options") res.send (200);    else next ();

and then the client is relatively simple, here I directly put App.js,controller.js and Servers.js merge show:

var main = angular.module (' Fruit_index ',  []). config ( function ($httpProvider)  {$httpProvider .defaults.usexdomain = true; delete $ HttpProvider.defaults.headers. common[' X-requested-with ']; }); Main.factory (' Mainservice ',  function ($http)  {return {getmaindata: function ()  {return   $http ({method:  ' post ', url:  ' http://localhost:3000/fruitpoint ', data: {base: {reqtime:   ' 201409041455123 ', prono:  ' 90002 '}, content: {mr_id:  ' 1234 '}, 
}}); } }; }); Main.controller ("Indexcontroller", Function ($scope, mainservice) {$scope. Name= "S"; Mainservice.getmaindata (). Success (function (data, status, headers) {console.log (data);}); });
<! doctype html> 

The static page of the call is a bit more, but the label of NG is quite simple.

Front End-"learning experience"-cross-domain issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.