简体   繁体   中英

How do I force Angular2 to return JS instead of HTML?

I have an express app calling an Angular2 app. I am consistently getting Error: (SystemJS) Unexpected token < and searching for a bit has led me to find that this is typically due to the wrong content-type being returned.

I found that app.module.js is returning html and not .js, is this what is throwing the code off?

Error: (SystemJS) Unexpected token <

The error in detail is:

dashboard:21 Error: (SystemJS) Unexpected token <
    SyntaxError: Unexpected token <
        at eval (<anonymous>)
        at Object.eval (http://localhost:3000/main.js:3:20)
        at eval (http://localhost:3000/main.js:8:4)
        at eval (http://localhost:3000/main.js:9:3)
    Evaluating http://localhost:3000/app/app.module.js
    Evaluating http://localhost:3000/main.js
    Error loading http://localhost:3000/main.js
        at eval (<anonymous>)
        at Object.eval (http://localhost:3000/main.js:3:20)
        at eval (http://localhost:3000/main.js:8:4)
        at eval (http://localhost:3000/main.js:9:3)
    Evaluating http://localhost:3000/app/app.module.js
    Evaluating http://localhost:3000/main.js
    Error loading http://localhost:3000/main.js

Here is a snapshot of it as dev tools for network: 在此处输入图片说明

This is what my express looks like:

app.use('/styles.css', express.static(path.join(__dirname, '../angular/src/styles.css')));
app.use('/systemjs.config.js', express.static(path.join(__dirname, '../angular/src/systemjs.config.js')));
app.use('/systemjs-angular-loader.js', express.static(path.join(__dirname, '../angular/src/systemjs-angular-loader.js')));
app.use('/systemjs.config.extras.js', express.static(path.join(__dirname, '../angular/src/systemjs.config.extras.js')));
app.use('/main.js.map', express.static(path.join(__dirname, '../angular/src/main.js.map')));

app.use('/main.js', express.static(path.join(__dirname, '../angular/src/main.js')));
app.use(express.static(path.join(__dirname, '../angular')));
app.use('/api/', auditlog);
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../angular/src/index.html'));
});

Your express app is set up to serve index.html to any request, so you'll get that file back when you might usually get a 404. Given the error, I'm guessing it likely that you have a missing JS file, or possibly some missing SystemJS module mappings. You can use the network inspector to find the missing file by looking in the preview tab of the request.

Consuming all routes is handy for Angular because of its routing, but it might be helpful to check if the client is requesting text/html before returning the app, returning 404 if not - This will make it easier to identify missing JS files on the client side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM